<?php

namespace app\mp\admin;

use app\common\service\GeneralMaterial as GeneralMaterialService;
use app\common\service\OrderMaterial as OrderMaterialService;
use app\common\service\Stock as StockService;
use app\common\service\StockLog as StockLogService;
use app\common\service\StockUse as StockUseService;
use app\system\admin\Admin;
use app\system\model\SystemRole as RoleModel;
use mes\Mes;
use think\Db;
use app\common\service\Order as OrderService;
use app\common\service\OrderSize as OrderSizeService;

/**
 * 委外管理》节点进度
 * @author zhuguosen 905502314@qq.com
 * @date 2021/12/4
 * @package app\mp\admin
 */
class OutNodeProgress extends Admin
{
    public $now;
    /**
     * @var \app\common\service\OrderOutgo
     */
    public $orderOutgoService;

    public function initialize()
    {
        parent::initialize();
        $this->now = time();
        $this->orderOutgoService = new \app\common\service\OrderOutgo();
    }

    /**
     * wx_order_outgo 的status说明
     * 待派工：100 设置完（分子工厂，委外参数设置） --已经不用了，后来加这状态，再后来就不用了。
     * 发货：110没发货 111发部分  对应 wx_order_outgo_cpl中的发货状态 --已经不用了，原先设计是这么构思的，代码也支持，但后来直接全部发货
     * 车缝中  200 2全部发货  201 确认回货
     * 后整中 300 对应上级201确认回货   301 已退货  302 外协尾部
     * 完成1000 对应旧系统逻辑
     */
    private function statusAll()
    {
        return;
    }

    /**
     * 外发管理》节点进度》待派工
     * @author zhuguosen 905502314@qq.com
     * @date 2022/3/18
     */
    public function dispatching()
    {
        if ($this->request->isAjax() || $this->request->param('export/d', 0) || $this->request->param('ajaxflag/d', 0) == 1) {
            $page = $this->request->param('page/d', 1);
            $limit = $this->request->param('limit/d', 20);
            $where = $this->_where_dispatching();
            $order = "o.id desc";
            $list = db('order o')
                ->field('ft.type as ft_type,ft.id as ft_id,ft.name as ft_name,g.id as g_id,g.name as g_name
                ,o.id,o.client_ordernum ,o.shipment_time,o.quantity,o.sku,o.type
                ,s.pic,s.ori_pic
                ,ds.status as status_distributing 
                ,sum(osize.shicai_count) sum_shicai_count ')
                ->join('order_outgo oot', "o.id=oot.order_id", 'left')
                ->join('factory ft', "ft.id=o.factory_id", 'left')
                ->join('group g', "oot.group_id=g.id", 'left')
                ->join('sku s', "o.sku=s.sku", 'left')
                ->join('distributing ds', "o.id=ds.order_id", 'left')
                ->join('order_size osize ', 'osize.order_id=o.id', 'left')
//                ->join('order_material om ', 'om.order_id=o.id', 'left')
//                ->join('material ml ', 'om.material_id=ml.id', 'left')
                ->where($where)->page($page)->limit($limit)->orderRaw($order)
                ->group('o.id')->select();
            $count = db('order o')
                ->join('order_outgo oot', "o.id=oot.order_id", 'left')
                ->join('factory ft', "ft.id=o.factory_id", 'left')
                ->join('group g', "oot.group_id=g.id", 'left')
                ->join('sku s', "o.sku=s.sku", 'left')
                ->join('distributing ds', "o.id=ds.order_id", 'left')
                ->join('order_size osize ', 'osize.order_id=o.id', 'left')
                ->where($where)
                ->group('o.id')->count();
            $orderMaterialService = new OrderMaterialService();
            $orderSizeService = new OrderSizeService();
            $stockService = new StockService();
            $generalMaterialService = new GeneralMaterialService();
            foreach ($list as $k => $v) {
                $list[$k]['pic_res'] = trim($v['ori_pic']) == '' ? $v['pic'] : $v['ori_pic'];
                $list[$k]['type_txt'] = arrayGet(config('mimo.order_type'), $v['type'], '');
                $list[$k]['shipment_time'] = intval($list[$k]['shipment_time']) <= 0 ? '' : date('m-d', $list[$k]['shipment_time']);//出货时间
                $list[$k]['status_distributing_txt'] = arrayGet(config('mimo.distributing_status'), $v['status_distributing'], '可发货');

                //同一个sku ,前三个订单有退货信息 ，或， 有三次以上的退货订单，就标识为 危

                //
                $omList = $orderMaterialService->getListByOrderId($v['id'], 'accessories');
                $omListMin = [];
                foreach ($omList as $k2 => &$material_info) {
                    $shicaiCount = $orderSizeService->getShicaiCount($v['id']);
                    // 需用量
                    $material_info['totalNum'] = $material_info['material_dosage'] * $shicaiCount;
                    // 库存现配量
                    $stockNum = $stockService->getStockLeft($material_info['material_id']);
                    $gmInfo = $generalMaterialService->getInfoByMaterialSku($material_info['mInfo']['material_sku']);
                    $stock = arrayGet($gmInfo, 'stock', 0);
                    $material_info['stockNum'] = $stockNum + $stock;
                    // 已使用量
                    $material_info['total_material_dosage'] = round(($v['quantity'] * $material_info['material_dosage']) + ($v['quantity'] * $material_info['material_dosage']) * $material_info['loss'] / 100, 2);

                    //欠数的材料才显示
//                    if ((($material_info['totalNum'] - $material_info['total_material_dosage']) - $material_info['stockNum']) > 0) {
                    $omListMin[] = [
                        'name' => $material_info['mInfo']['name'],
                        'material_sku' => $material_info['mInfo']['material_sku'],
                        'color' => $material_info['mInfo']['color'],
                        'totalNum' => $material_info['totalNum'],//需用量
                        'stockNum' => $material_info['stockNum'],//库存现配量
                        'total_material_dosage' => $material_info['total_material_dosage'],//总用量
                    ];
//                    }
                }
                $list[$k]['omListMin'] = $omListMin;
                //查询子工厂信息
                $groupList = db('group')->field('id,name')->where([
                    ['factory_id', '=', $v['ft_id']],
                ])->column('id,name');
                $list[$k]['groupList'] = [0 => '请选择'] + $groupList;
            }
            $list_last = [];
            foreach ($list as $k => $v) {
                $list_last["_{$v['client_ordernum']}"] = $v;
            }
            //获取各状态统计数据
            $status_sum = $this->_status_sum_dispatching($where);
            $result = [
                'code' => 0,
                'msg' => '',
                'data' => $list_last,
                'pageInfo' => [
                    'count' => $count,
                    'maxPage' => ceil($count / $limit),
                ],
                'txt' => [
                ],
                'status_sum' => $status_sum,
            ];
            return json($result);
        }

        $assign = [
            'factoryAll' => $this->_factorylist([
                'ft_type' => 1,
            ], true),
            'client_ordernum' => $this->request->param('client_ordernum/s', ''),
            'sku' => $this->request->param('sku/s', ''),
        ];
        foreach ($assign['factoryAll'] as $k => $v) {
            $assign['factoryAll'][$k]['children'] = [];
        }
        return $this->assign($assign)->fetch();
    }

    private function _where_dispatching()
    {
        $where = [
            ['ft.type', '=', 1],
            ["o.status", 'in', [0, 1]],
            ["o.client_status", '<>', 99],
            ['o.chejian_status', '=', 0],
            ['oot.update_time', '>', strtotime('2022-01-05')],//只是最新订单才有效
            ["oot.status", "<", 200],
        ];
        //订单加一级
        order_level($where, 'o.');
        $clientOrdernum = $this->request->param('client_ordernum/s', '');
        $sku = $this->request->param('sku/s', '');
        $createDateRange = $this->request->param('create_date_range/s', '');
        $factory_all = trim($this->request->param('factory_all'));
        if ($clientOrdernum != '') {
            $where[] = ['o.client_ordernum', 'like', "%" . $clientOrdernum . "%"];
        }
        if ($sku != '') {
            $where[] = ['o.sku', 'like', "%" . $sku . "%"];
        }
        if ($createDateRange != '') {
            list($startTime, $endTime) = array_map('strtotime', explode('~', $createDateRange));
            $where[] = ['o.create_time', 'between', [$startTime, $endTime + 86399]];
        }
        if ($factory_all != '') {
            $factory_all_array = explode(',', $factory_all);
            foreach ($factory_all_array as $k => $v) {
                $factory_all_array[$k] = -intval($v);
            }
            $where[] = ['o.factory_id', 'in', $factory_all_array];
        }
        return $where;
    }

    private function _status_sum_dispatching($where)
    {
        $list_0 = db('order o')
            ->field('o.id,o.quantity')
            ->join('order_outgo oot', "o.id=oot.order_id", 'left')
            ->join('factory ft', "ft.id=o.factory_id", 'left')
            ->join('group g', "oot.group_id=g.id", 'left')
            ->join('sku s', "o.sku=s.sku", 'left')
            ->join('distributing ds', "o.id=ds.order_id", 'left')
            ->join('order_size osize ', 'osize.order_id=o.id', 'left')
            ->join('order_material om ', 'om.order_id=o.id', 'left')
            ->join('material ml ', 'om.material_id=ml.id', 'left')
            ->where($where)
            ->group('o.id')->select();
        $info_0 = [
            'count' => 0,
            'sum_quantity' => 0,
        ];
        foreach ($list_0 as $k => $v) {
            $info_0['count']++;
            $info_0['sum_quantity'] += $v['quantity'];
        }
        $res = [];
        $res[] = [
            'name' => '待派工',
            'count' => $info_0['count'],
            'sum_quantity' => floatval($info_0['sum_quantity']),
        ];
        return $res;
    }

    /**
     * 外发管理》节点进度》采购
     * @date 2021/11/17
     * @author zhuguosen 905502314@qq.com
     */
    public function index()
    {
        if ($this->request->isAjax() || $this->request->param('export/d', 0) || $this->request->param('ajaxflag/d', 0) == 1) {
            $page = $this->request->param('page/d', 1);
            $limit = $this->request->param('limit/d', 20);
            $nodeData = $this->nodeSetAndView('index');
            if ($nodeData['code'] > 0) {
                return json($nodeData);
            }
            $where = $this->_where_index();
            $order = "FIELD(o.status,2,99) ASC,o.caigou_status ASC, o.create_time ASC";
            $list = db('order o')
                ->field('ft.type as ft_type,ft.id as ft_id,ft.name as ft_name,g.id as g_id,g.name as g_name
                ,o.id,o.client_ordernum ,o.shipment_time,o.quantity
                ,s.pic')
                ->join('factory ft', "ft.id=o.factory_id", 'left')
                ->join('order_outgo oot', "oot.order_id=o.id", 'left')
                ->join('group g', "oot.group_id=g.id", 'left')
                ->join('sku s', "o.sku=s.sku", 'left')
                ->join('order_material om ', 'om.order_id=o.id', 'left')
                ->join('material ml ', 'om.material_id=ml.id', 'left')
                ->where($where)->page($page)->limit($limit)->orderRaw($order)->group('o.id')->select();
            $count = db('order o')
                ->field('ft.type as ft_type,ft.name as ft_name,o.id,o.client_ordernum ,o.shipment_time,o.quantity
                ,s.pic')
                ->join('factory ft', "ft.id=o.factory_id", 'left')
                ->join('order_outgo oot', "oot.order_id=o.id", 'left')
                ->join('sku s', "o.sku=s.sku", 'left')
                ->join('order_material om ', 'om.order_id=o.id', 'left')
                ->join('material ml ', 'om.material_id=ml.id', 'left')
                ->where($where)->group('o.id')->count();
            foreach ($list as $k => $v) {
                //注释说明
                $sql = "select om.mid, om.material_id , om.arrive_time, om.is_make_tag, om.tiaoshu tiaoshu_条数, om.shiji_caigou_count shiji_caigou_count_实际到总条数  ,om.update_time update_time_操作时间
                    ,ml.supplier,ml.type,ml.name,ml.material_sku
                    ,omi.cloth_num,omi.is_checkcloth,omi.is_checkcloth ,omi.need_shrink,omi.is_shrink_outgo,omi.is_shrink （暂时没用了）
                    ,stl.id as storck_id_table
                     from wx_order_material om 
                     left join  wx_material ml on (om.material_id=ml.id)
                     left join  wx_order_material_item omi on (om.mid=omi.order_material_id)
                     left join  wx_stock_log stl on (stl.order_id=om.order_id and  om.material_id=stl.material_id and stl.type=1)
                     where om.order_id = {$v['id']} and om.material_id > 0  and om.caigou_show=1 (去除不在采购进度显示条目)
                     order by om.caichuang_standard desc ";
                //获取材料列表
                $sql = "select om.mid, om.material_id , om.arrive_time, om.is_make_tag, om.tiaoshu, om.shiji_caigou_count  ,om.update_time
                    ,ml.supplier,ml.type,ml.name,ml.material_sku
                    ,omi.cloth_num,omi.is_checkcloth,omi.is_checkcloth ,omi.need_shrink,omi.is_shrink_outgo,omi.is_shrink
                    ,stl.id as storck_id_table
                     from wx_order_material om 
                     left join  wx_material ml on (om.material_id=ml.id)
                     left join  wx_order_material_item omi on (om.mid=omi.order_material_id)
                     left join  wx_stock_log stl on (stl.order_id=om.order_id and  om.material_id=stl.material_id and stl.type=1)
                     where om.order_id = {$v['id']} and om.material_id > 0  and om.caigou_show=1
                     order by om.caichuang_standard desc ";
                $omList = db()->query($sql);
                $res_omlist = $this->_dealwith_omList($omList);
                $list[$k]['zhu_status_int'] = $res_omlist['zhu_status_int'];
                $list[$k]['fu_status_int'] = $res_omlist['fu_status_int'];
                $list[$k]['omList'] = $res_omlist['resList'];
                $list[$k]['shipment_time'] = intval($list[$k]['shipment_time']) <= 0 ? '' : date('m-d', $list[$k]['shipment_time']);//出货时间
                //查询子工厂信息
                $groupList = db('group')->field('id,name')->where([
                    ['factory_id', '=', $v['ft_id']],
                ])->column('id,name');
                $list[$k]['groupList'] = [0 => '请选择'] + $groupList;
            }
            $list_last = [];
            foreach ($list as $k => $v) {
                $list_last["_{$v['client_ordernum']}"] = $v;
            }
            $result = [
                'code' => 0,
                'msg' => '',
                'data' => $list_last,
                'pageInfo' => [
                    'count' => $count,
                    'maxPage' => ceil($count / $limit),
                ],
                'txt' => [
                    'material_type' => config('mimo.material_type'),
                    'arrive_flag' => [0 => '', 1 => '到料',],
                ],
            ];
            return json($result);
        }
        $assign = [
            'client_ordernum' => $this->request->param('client_ordernum/s', ''),
            'sku' => $this->request->param('sku/s', ''),
        ];
        return $this->assign($assign)->fetch();
    }

    private function _where_index()
    {
        $where = [
            ['ft.type', '=', 1],
            ['ml.type', '=', 'fabric'],
//            ['om.caichuang_can_do', '=', 0],
            ["oot.status", "<=", 100],
        ];
        $where[] = ['om.caichuang_can_do', '=', 0];//与裁剪中的订单切开一下
        //订单加一级
        order_level($where, 'o.');
        $page = $this->request->param('page/d', 1);
        $limit = $this->request->param('limit/d', 20);
//        $where[] = ['o.id', '>', 92009];//只是最新订单才有效
        $where[] = ['oot.update_time', '>', strtotime('2022-01-05')];//只是最新订单才有效
        $where[] = ['o.caichuang_status', '=', 0];//到了待发货节点，就不显示了
        $clientOrdernum = $this->request->param('client_ordernum/s', '');
        $sku = $this->request->param('sku/s', '');
        $createDateRange = $this->request->param('create_date_range/s', '');
        $material_type = $this->request->param('material_type/d', 0);
        $material_status = $this->request->param('material_status/d', 0);

        if ($clientOrdernum == '') {
            $where[] = ["o.status", 'in', [0, 1]];
        }
        $where[] = ["o.client_status", '<>', 99];
        if ($clientOrdernum != '') {
            $where[] = ['o.client_ordernum', 'like', "%" . $clientOrdernum . "%"];
        }
        if ($sku != '') {
            $where[] = ['o.sku', 'like', "%" . $sku . "%"];
        }
        if ($createDateRange != '') {
            list($startTime, $endTime) = array_map('strtotime', explode('~', $createDateRange));
            $where[] = ['o.create_time', 'between', [$startTime, $endTime + 86399]];
        }
        //放到最后的搜索条件
        if ($material_type > 0 && $material_status > 0) {
            switch ($material_status) {
                case 1://采购中
                    $where_om = $where;
                    $where_om[] = ['om.material_id', '>', 0];
                    $where_om[] = ['om.caigou_show', '=', 1];
                    $where_om[] = ['om.arrive_time', '=', 0];
                    if ($material_type == 1) {//主料
                        $where_om[] = ['ml.type', 'in', ['fabric', 'lining']];
                    }
                    if ($material_type == 2) {//辅料
                        $where_om[] = ['ml.type', '=', 'accessories'];
                    }
                    $order_ids = db('order_material om')
                        ->field('om.order_id,om.arrive_time')
                        ->join('wx_order o', "om.order_id=o.id", 'left')
                        ->join('wx_material ml', "om.material_id=ml.id", 'left')
                        ->where($where_om)
                        ->page($page)->limit($limit * 10)
                        ->orderRaw('FIELD(o.status,2,99) ASC,o.caigou_status ASC, o.create_time ASC ,om.caichuang_standard desc')->select();
                    if (count($order_ids) > 0) {
                        $where_om_2 = $where_om;
                        foreach ($where_om_2 as $k => $v) {
                            if ($v[0] == 'om.arrive_time') {
                                unset($where_om_2[$k]);
                            }
                        }
                        $where_om_2[] = ['om.arrive_time', '>', 0];
                        $order_ids_2 = db('order_material om')
                            ->field('om.order_id,om.arrive_time')
                            ->join('wx_order o', "om.order_id=o.id", 'left')
                            ->join('wx_material ml', "om.material_id=ml.id", 'left')
                            ->where($where_om_2)
                            ->page($page)->limit($limit * 10)
                            ->orderRaw('FIELD(o.status,2,99) ASC,o.caigou_status ASC, o.create_time ASC ,om.caichuang_standard desc')->select();
                        $temp = [];
                        foreach ($order_ids as $k => $v) {
                            $flag = 0;
                            foreach ($order_ids_2 as $k2 => $v2) {
                                if ($v['order_id'] == $v2['order_id']) {
                                    $flag = 1;
                                    break;
                                }
                            }
                            $flag == 0 && $temp[] = $v['order_id'];
                        }
                        $where[] = ['o.id', 'in', $temp];
                    }
                    break;
                case 2://未回齐
                    $where_om = $where;
                    $where_om[] = ['om.material_id', '>', 0];
                    $where_om[] = ['om.caigou_show', '=', 1];
                    $where_om[] = ['om.arrive_time', '=', 0];
                    if ($material_type == 1) {//主料
                        $where_om[] = ['ml.type', 'in', ['fabric', 'lining']];
                    }
                    if ($material_type == 2) {//辅料
                        $where_om[] = ['ml.type', '=', 'accessories'];
                    }
                    $order_ids = db('order_material om')
                        ->field('om.order_id,om.arrive_time')
                        ->join('wx_order o', "om.order_id=o.id", 'left')
                        ->join('wx_material ml', "om.material_id=ml.id", 'left')
                        ->where($where_om)
                        ->page($page)->limit($limit * 10)
                        ->orderRaw('FIELD(o.status,2,99) ASC,o.caigou_status ASC, o.create_time ASC ,om.caichuang_standard desc')->select();
                    if (count($order_ids) > 0) {
                        $where_om_2 = $where_om;
                        foreach ($where_om_2 as $k => $v) {
                            if ($v[0] == 'om.arrive_time') {
                                unset($where_om_2[$k]);
                            }
                        }
                        $where_om_2[] = ['om.arrive_time', '>', 0];
                        $order_ids_2 = db('order_material om')
                            ->field('om.order_id,om.arrive_time')
                            ->join('wx_order o', "om.order_id=o.id", 'left')
                            ->join('wx_material ml', "om.material_id=ml.id", 'left')
                            ->where($where_om_2)
                            ->page($page)->limit($limit * 10)
                            ->orderRaw('FIELD(o.status,2,99) ASC,o.caigou_status ASC, o.create_time ASC ,om.caichuang_standard desc')->select();
                        $temp = [];
                        foreach ($order_ids as $k => $v) {
                            $flag = 0;
                            foreach ($order_ids_2 as $k2 => $v2) {
                                if ($v['order_id'] == $v2['order_id']) {
                                    $flag = 1;
                                    break;
                                }
                            }
                            $flag == 1 && $temp[] = $v['order_id'];
                        }
                        $where[] = ['o.id', 'in', $temp];
                    }
                    break;
                case 3://已回齐
                    $where_om = $where;
                    $where_om[] = ['om.material_id', '>', 0];
                    $where_om[] = ['om.caigou_show', '=', 1];
                    $where_om[] = ['om.arrive_time', '>', 0];
                    if ($material_type == 1) {//主料
                        $where_om[] = ['ml.type', 'in', ['fabric', 'lining']];
                    }
                    if ($material_type == 2) {//辅料
                        $where_om[] = ['ml.type', '=', 'accessories'];
                        $where_om[] = ['stl.id', 'not null', ''];
                    }
                    $order_ids = db('order_material om')
                        ->field('om.order_id,om.arrive_time,stl.id as storck_id_table')
                        ->join('wx_order o', "om.order_id=o.id", 'left')
                        ->join('wx_material ml', "om.material_id=ml.id", 'left')
                        ->join(' wx_stock_log stl', "stl.order_id=om.order_id and  om.material_id=stl.material_id and stl.type=1", 'left')
                        ->where($where_om)
                        ->page($page)->limit($limit * 10)
                        ->orderRaw('FIELD(o.status,2,99) ASC,o.caigou_status ASC, o.create_time ASC ,om.caichuang_standard desc')->select();
                    if (count($order_ids) > 0) {
                        $where_om_2 = $where_om;
                        foreach ($where_om_2 as $k => $v) {
                            if ($v[0] == 'om.arrive_time') {
                                unset($where_om_2[$k]);
                            }
                            if ($material_type == 2 && $v[0] == 'stl.id') {//辅料
                                unset($where_om_2[$k]);
                            }
                        }
                        $material_type == 1 && $where_om_2[] = ['om.arrive_time', '=', 0];
                        if ($material_type == 2) {//辅料
                            $where_om_2[] = ['om.arrive_time', '>', 0];
                            $where_om_2[] = ['stl.id', 'null', ''];
                        }
                        $order_ids_2 = db('order_material om')
                            ->field('om.order_id,om.arrive_time')
                            ->join('wx_order o', "om.order_id=o.id", 'left')
                            ->join('wx_material ml', "om.material_id=ml.id", 'left')
                            ->join(' wx_stock_log stl', "stl.order_id=om.order_id and  om.material_id=stl.material_id and stl.type=1", 'left')
                            ->where($where_om_2)
                            ->page($page)->limit($limit * 10)
                            ->orderRaw('FIELD(o.status,2,99) ASC,o.caigou_status ASC, o.create_time ASC ,om.caichuang_standard desc')->select();
                        $temp = [];
                        foreach ($order_ids as $k => $v) {
                            $flag = 0;
                            foreach ($order_ids_2 as $k2 => $v2) {
                                if ($v['order_id'] == $v2['order_id']) {
                                    $flag = 1;
                                    break;
                                }
                            }
                            $flag == 0 && $temp[] = $v['order_id'];
                        }
                        $where[] = ['o.id', 'in', $temp];
                    }
                    break;
            }
        }
        return $where;
    }

    private function _dealwith_omList($omList)
    {
        $resList = [];
        //1,以wx_order_material_item为最小单位 处理，因为 wx_stock_log可能变多数据。
        $temp = [];
        foreach ($omList as $k => $v) {
            $temp["{$v['material_sku']}_{$v['cloth_num']}"] = $v;
        }
        $omList = $temp;
        //2,材料与布号信息 变为 父子关系信息结构
        foreach ($omList as $k => $v) {
            $material_info = $v;
            $resList[$v['material_sku']]['material_info'] = $material_info;
        }
        foreach ($omList as $k => $v) {
            $order_material_item_info = $v;
            $resList[$v['material_sku']]['order_material_item'][$v['cloth_num']] = $order_material_item_info;
        }
        //3,主料与辅料的状态信息 算出
        //3.1,主料状态 算出
        $zhu_status = [];
        foreach ($resList as $k => $v) {
            if ($v['material_info']['type'] == 'fabric' || $v['material_info']['type'] == 'lining') {
                $zhu_status[] = $v['material_info']['arrive_time'];
            }
        }
        $zhu_status_int = 1;//1采购中 2未回齐 3已回齐
        $flag = 0;
        foreach ($zhu_status as $k => $v) {
            if ($v > 0) {
                $zhu_status_int = 2;
            } else {
                $flag = 1;
            }
        }
        if ($flag == 0) {//所有到料后，才算是否已回齐
            $zhu_status_int = 3;
        }
        //3.2,辅料状态 算出
        $fu_status = [];
        $fu_stock_status = [];
        foreach ($resList as $k => $v) {
            if ($v['material_info']['type'] == 'accessories') {
                $fu_status[] = $v['material_info']['arrive_time'];
                $fu_stock_status[$k] = $v['material_info']['storck_id_table'];
            }
        }
        $fu_status_int = 1;//1采购中 2未回齐 3已回齐
        $flag = 0;
        foreach ($fu_status as $k => $v) {
            if ($v > 0) {
                $fu_status_int = 2;
            } else {
                $flag = 1;
            }
        }
        if ($flag == 0) {//所有到料后，才算是否已回齐  辅料为都入库才算回齐
            $temp = 0;
            foreach ($fu_stock_status as $k => $v) {
                if (intval($v) == 0) {
                    $temp = 1;
                    break;
                }
            }
            if ($temp == 0) {
                $fu_status_int = 3;
            }
        }
        //4,布号信息处理 字段已有了，只是格式处理
        foreach ($resList as $k => $v) {
            $resList[$k]['material_info']['update_time'] = date('Y-m-d H:i:s', $resList[$k]['material_info']['update_time']);
            if (intval($resList[$k]['material_info']['arrive_time']) == 0) {
                $resList[$k]['material_info']['arrive_flag'] = 0;
                $resList[$k]['material_info']['arrive_time'] = '';
            } else {
                $resList[$k]['material_info']['arrive_flag'] = 1;
                $resList[$k]['material_info']['arrive_time'] = date('Y-m-d H:i:s', $resList[$k]['material_info']['arrive_time']);
            }
        }
        return [
            'zhu_status_int' => $zhu_status_int,
            'fu_status_int' => $fu_status_int,
            'resList' => $resList,
        ];
    }

    /**
     * 外发管理》节点进度》裁剪中
     * @date 2021/11/19
     * @author zhuguosen 905502314@qq.com
     */
    public function cutting()
    {
        if ($this->request->isAjax() || $this->request->param('export/d', 0)) {
            $page = $this->request->param('page/d', 1);
            $limit = $this->request->param('limit/d', 20);
            $nodeData = $this->nodeSetAndView('cutting');
            if ($nodeData['code'] > 0) {
                return json($nodeData);
            }
            $where = $this->_where_cutting();
            $order = "o.shipment_time ASC,o.create_time ASC";
            $list = db('order o')
                ->field('ft.type as ft_type,ft.id as ft_id,ft.name as ft_name,g.id as g_id,g.name as g_name
                ,o.id,o.client_ordernum ,o.shipment_time,o.quantity,o.sku,o.type
                ,s.pic 
                ,oot.hope_shipment_time ')
                ->join('factory ft', "ft.id=o.factory_id", 'left')
                ->join('sku s', "o.sku=s.sku", 'left')
                ->join('order_outgo oot', "o.id=oot.order_id", 'left')
                ->join('group g', "oot.group_id=g.id", 'left')
                ->join('wx_order_material om ', 'om.order_id=o.id', 'left')
                ->join('wx_material ml ', 'om.material_id=ml.id', 'left')
                ->where($where)->page($page)->limit($limit)->orderRaw($order)
                ->group('om.order_id')
                ->select();
            $count = db('order o')
                ->field('o.id')
                ->join('factory ft', "ft.id=o.factory_id", 'left')
                ->join('sku s', "o.sku=s.sku", 'left')
                ->join('order_outgo oot', "o.id=oot.order_id", 'left')
                ->join('wx_order_material om ', 'om.order_id=o.id', 'left')
                ->join('wx_material ml ', 'om.material_id=ml.id', 'left')
                ->where($where)->group('om.order_id')->count('o.id');
            foreach ($list as $k => $v) {
                $list[$k]['type_txt'] = arrayGet(config('mimo.order_type'), $v['type'], '');
                $list[$k]['shipment_time'] = intval($list[$k]['shipment_time']) <= 0 ? '' : date('m-d', $list[$k]['shipment_time']);//出货时间
                //查询子工厂信息
                $groupList = db('group')->field('id,name')->where([
                    ['factory_id', '=', $v['ft_id']],
                ])->column('id,name');
                $list[$k]['groupList'] = [0 => '请选择'] + $groupList;
            }
            $list_last = [];
            foreach ($list as $k => $v) {
                $list_last["_{$v['client_ordernum']}"] = $v;
            }
            $result = [
                'code' => 0,
                'msg' => '',
                'data' => $list_last,
                'pageInfo' => [
                    'count' => $count,
                    'maxPage' => ceil($count / $limit),
                ],
                'txt' => [
                    'order_type' => config('mimo.order_type')
                ],
            ];
            return json($result);
        }
        $assign = [
            'orderFrom' => [0 => '请选择'] + config('mimo.order_from'),
            'client_ordernum' => $this->request->param('client_ordernum/s', ''),
            'sku' => $this->request->param('sku/s', ''),
        ];
        return $this->assign($assign)->fetch();
    }

    private function _where_cutting()
    {
        $where = [
            ['ft.type', '=', 1],
            ["oot.status", "<=", 100],
        ];
        //订单加一级
        order_level($where, 'o.');
//        $where[] = ['o.id', '>', 92009];//只是最新订单才有效
        $where[] = ['oot.update_time', '>', strtotime('2022-01-05')];//只是最新订单才有效
        $where[] = ['ml.type', '=', 'fabric'];
        $where[] = ['om.caichuang_can_do', '=', 1];//面料可裁就是 裁剪中
        $where[] = ['om.caichuang_pull_status', '=', 0];//裁床拉布状态（0未确认，1已确认） 0就是没完成  1就是裁床完成了
        $where[] = ['o.outgo_status', '=', 0];//区分旧外发，还是这里最新的外发。
        $where[] = ['o.caichuang_status', '=', 0];

        $page = $this->request->param('page/d', 1);
        $limit = $this->request->param('limit/d', 20);
        $clientOrdernum = $this->request->param('client_ordernum/s', '');
        $sku = $this->request->param('sku/s', '');
        $createDateRange = $this->request->param('create_date_range/s', '');
        $shipment_date_range = $this->request->param('shipment_date_range/s', '');
        $is_auto_import = $this->request->param('is_auto_import/d', 0);
        if ($clientOrdernum == '') {
            $where[] = ["o.status", 'in', [0, 1]];
        }
        $where[] = ["o.client_status", '<>', 99];
        if ($clientOrdernum != '') {
            $where[] = ['o.client_ordernum', 'like', "%" . $clientOrdernum . "%"];
        }
        if ($sku != '') {
            $where[] = ['o.sku', 'like', "%" . $sku . "%"];
        }
        if ($createDateRange != '') {
            list($startTime, $endTime) = array_map('strtotime', explode('~', $createDateRange));
            $where[] = ['o.create_time', 'between', [$startTime, $endTime + 86399]];
        }
        if ($shipment_date_range != '') {
            list($startTime, $endTime) = array_map('strtotime', explode('~', $shipment_date_range));
            $where[] = ['o.shipment_time', 'between', [$startTime, $endTime + 86399]];
        }
        if ($is_auto_import > 0) {
            $where[] = ['o.is_auto_import', '=', $is_auto_import];
        }
        return $where;
    }

    /**
     * 设置  裁剪中=》工厂预交期   车缝中=》回货时间  外协尾部=》回货时间
     * @date 2021/11/25
     * @author zhuguosen 905502314@qq.com
     */
    public function setHopeShipmentTime()
    {
        $clientOrdernum = $this->request->param('client_ordernum/s', '');
        $date_time = strtotime($this->request->param('date_time', '') . " 23:59:59");
        $field = $this->request->param('field/s', 'hope_shipment_time');
        $info = db('order o')
            ->field('o.id,o.client_ordernum')
            ->where([
                ['o.client_ordernum', '=', $clientOrdernum],
                ['o.status', '=', 1],//99作废
            ])->find();
        if (!isset($info['id'])) {
            return $this->json(10, '请传client_ordernum');
        }
        $temp = db('order_outgo oot')->where([
            ['oot.order_id', '=', $info['id']]
        ])->update([
            $field => $date_time,
//            'update_time' => time(),
        ]);
        if ($temp == 0) {
            return $this->json(11, '设置失败');
        }
        return $this->json(1, '设置成功');
    }

    /**
     * 外发管理》节点进度》待发货
     * @date 2021/11/20
     * @author zhuguosen 905502314@qq.com
     */
    public function waitDeliver()
    {
        if ($this->request->isAjax() || $this->request->param('export/d', 0) || $this->request->param('ajaxflag/d', 0) == 1) {
            $page = $this->request->param('page/d', 1);
            $limit = $this->request->param('limit/d', 20);
            $nodeData = $this->nodeSetAndView('waitDeliver');
            if ($nodeData['code'] > 0) {
                return json($nodeData);
            }
            $where = $this->_where_waitDeliver();
            $order = "ds.create_time asc";
            $list = db('order o')
                ->field('ft.type as ft_type,ft.id as ft_id,ft.name as ft_name,g.id as g_id,g.name as g_name
                ,o.id,o.client_ordernum ,o.shipment_time,o.quantity,o.sku,o.type
                ,s.pic,s.ori_pic
                ,ds.status as status_distributing 
                ,sum(osize.shicai_count) sum_shicai_count ')
                ->join('order_outgo oot', "o.id=oot.order_id", 'left')
                ->join('factory ft', "ft.id=o.factory_id", 'left')
                ->join('group g', "oot.group_id=g.id", 'left')
                ->join('sku s', "o.sku=s.sku", 'left')
                ->join('distributing ds', "o.id=ds.order_id", 'left')
                ->join('order_size osize ', 'osize.order_id=o.id', 'left')
                ->where($where)->page($page)->limit($limit)->orderRaw($order)
                ->group('o.id')->select();
            $count = db('order o')
                ->join('order_outgo oot', "o.id=oot.order_id", 'left')
                ->join('factory ft', "ft.id=o.factory_id", 'left')
                ->join('sku s', "o.sku=s.sku", 'left')
                ->join('distributing ds', "o.id=ds.order_id", 'left')
                ->join('order_size osize ', 'osize.order_id=o.id', 'left')
                ->where($where)
                ->group('o.id')->count();;
            $orderMaterialService = new OrderMaterialService();
            $orderSizeService = new OrderSizeService();
            $orderService = new OrderService();
            $stockService = new StockService();
            $generalMaterialService = new GeneralMaterialService();
            $stockLogService = new StockLogService();
            $stockUseService = new StockUseService();
            foreach ($list as $k => $v) {
                $list[$k]['pic_res'] = trim($v['ori_pic']) == '' ? $v['pic'] : $v['ori_pic'];
                $list[$k]['type_txt'] = arrayGet(config('mimo.order_type'), $v['type'], '');
                $list[$k]['shipment_time'] = intval($list[$k]['shipment_time']) <= 0 ? '' : date('m-d', $list[$k]['shipment_time']);//出货时间
                $list[$k]['status_distributing_txt'] = arrayGet(config('mimo.distributing_status'), $v['status_distributing'], '可发货');

                //同一个sku ,前三个订单有退货信息 ，或， 有三次以上的退货订单，就标识为 危

                //
                $omList = $orderMaterialService->getListByOrderId($v['id'], 'accessories');
                $omListMin = [];
                foreach ($omList as $k2 => &$material_info) {
                    $shicaiCount = $orderSizeService->getShicaiCount($v['id']);
                    // 需用量
                    $material_info['totalNum'] = $material_info['material_dosage'] * $shicaiCount;
                    // 库存现配量
                    $stockNum = $stockService->getStockLeft($material_info['material_id']);
                    $gmInfo = $generalMaterialService->getInfoByMaterialSku($material_info['mInfo']['material_sku']);
                    $stock = arrayGet($gmInfo, 'stock', 0);
                    $material_info['stockNum'] = $stockNum + $stock;
                    // 已使用量
                    $material_info['total_material_dosage'] = round(($v['quantity'] * $material_info['material_dosage']) + ($v['quantity'] * $material_info['material_dosage']) * $material_info['loss'] / 100, 2);

                    //欠数的材料才显示
//                    if ((($material_info['totalNum'] - $material_info['total_material_dosage']) - $material_info['stockNum']) > 0) {
                    $omListMin[] = [
                        'name' => $material_info['mInfo']['name'],
                        'material_sku' => $material_info['mInfo']['material_sku'],
                        'color' => $material_info['mInfo']['color'],
                        'totalNum' => $material_info['totalNum'],//需用量
                        'stockNum' => $material_info['stockNum'],//库存现配量
                        'total_material_dosage' => $material_info['total_material_dosage'],//总用量
                    ];
//                    }
                }
                $list[$k]['omListMin'] = $omListMin;
                //查询子工厂信息
                $groupList = db('group')->field('id,name')->where([
                    ['factory_id', '=', $v['ft_id']],
                ])->column('id,name');
                $list[$k]['groupList'] = [0 => '请选择'] + $groupList;
            }
            //获取各状态统计数据
            $status_sum = $this->_status_sum_waitDeliver($where);
            $list_last = [];
            foreach ($list as $k => $v) {
                $list_last["_{$v['client_ordernum']}"] = $v;
            }
            $result = [
                'code' => 0,
                'msg' => '',
                'data' => $list_last,
                'pageInfo' => [
                    'count' => $count,
                    'maxPage' => ceil($count / $limit),
                ],
                'txt' => [
                ],
                'status_sum' => $status_sum,
            ];
            return json($result);
        }
        $assign = [
            'client_ordernum' => $this->request->param('client_ordernum/s', ''),
            'sku' => $this->request->param('sku/s', ''),
        ];
        return $this->assign($assign)->fetch();
    }

    private function _status_sum_waitDeliver($where)
    {
        $list = db('order o')
            ->field('ds.status as status_distributing ,count(o.id) as count,sum(o.quantity) as sum_quantity ')
            ->join('order_outgo oot', "o.id=oot.order_id", 'left')
            ->join('factory ft', "ft.id=o.factory_id", 'left')
            ->join('sku s', "o.sku=s.sku", 'left')
            ->join('distributing ds', "o.id=ds.order_id", 'left')
//            ->join('order_size osize ', 'osize.order_id=o.id', 'left') //多条
            ->where($where)
            ->group('ds.status')
            ->select();
        $res = [];
        foreach ($list as $k => $v) {
            $res[] = [
                'name' => arrayGet(config('mimo.distributing_status'), $v['status_distributing'], '可发货'),
                'count' => $v['count'],
                'sum_quantity' => floatval($v['sum_quantity']),
            ];
        }
        return $res;
    }

    private function _where_waitDeliver()
    {
        $where = [
            ['ft.type', '=', 1],
            ['o.caichuang_over_time', '<>', 0],
            ['o.status', '<>', 99],
            ['o.stock_type', 'not in', '10,11'],
            ["oot.status", "<=", 100],
        ];
        //订单加一级
        order_level($where, 'o.');
//        $where[] = ['o.id', '>', 92009];//只是最新订单才有效
        $where[] = ['oot.update_time', '>', strtotime('2022-01-05')];//只是最新订单才有效
        $where[] = ["oot.status", "<", 200];
        $where[] = ["o.status", 'in', [0, 1]];

        $where[] = ["o.status", 'in', [0, 1, 2]];
        $where[] = ['o.caichuang_status', '=', 1];
        $where[] = ['o.outgo_status', '=', 0];

//        $where[] = ["ds.status", "<", 5];
        $clientOrdernum = $this->request->param('client_ordernum/s', '');
        $sku = $this->request->param('sku/s', '');
        if ($clientOrdernum == '') {
            $where[] = ['o.status', '<>', 99];
        }
        if ($clientOrdernum != '') {
            $where[] = ['o.client_ordernum', 'like', "%" . $clientOrdernum . "%"];
        }
        if ($sku != '') {
            $where[] = ['o.sku', 'like', "%" . $sku . "%"];
        }
        return $where;
    }

    public function wait_deliver_data_init()
    {
        set_time_limit(0);
        ini_set('memory_limit', '512M');
        error_reporting(E_ALL & ~E_NOTICE);
        $page = 1;
        for ($page = 1; $page < 1000000; $page++) {
            $where = [
                ['ft.type', '=', 1],
//                ["oot.status",'=', "null"],
            ];
            $list = db('order o')
                ->field('o.id,o.client_ordernum , oot.status')
                ->join('order_outgo oot', "o.id=oot.order_id", 'left')
                ->join('factory ft', "ft.id=o.factory_id", 'left')
                ->join('distributing ds', "o.id=ds.order_id", 'left')
                ->where($where)->page($page)->limit(10)
                ->group('o.id')
                ->select();
            if (count($list) <= 0) {
                return $this->json(1, '', $page);
            }
            foreach ($list as $k => $v) {
                if (trim($v['status']) == '') {
                    $res = $this->orderOutgoService->waitDeliver_data_init($v['id'], 0);
                }
            }
        }
        return $this->json(1, '', $page);
    }

    /**
     * 外发管理》节点进度》待发货 --确认发货-窗口-弹出
     * @date 2021/12/10
     * @author zhuguosen 905502314@qq.com
     */
    public function waitDeliverCutPackageLabelGet()
    {
        //1,参数处理
        $client_ordernum_all = $this->request->param('client_ordernum_all/s', '');
        if ($client_ordernum_all == '') {
            return $this->json(10, '请选择订单', []);
        }
        $client_ordernum_all_array = explode(',', $client_ordernum_all);
        //2,查询信息
        $where = [
            ['o.status', '=', 1],//99作废
            ['o.client_ordernum', 'in', $client_ordernum_all_array],
            ['ooc.status', '=', 0],
            ['ooc.status_send', '=', 0],
        ];
        $list = $this->_waitDeliverCutPackageLabelGet($where);
        //3,如没信息的，就整单发。就是自动生成一个1个
        foreach ($client_ordernum_all_array as $k => $v) {
            $flag = 0;
            foreach ($list as $k2 => $v2) {
                if ($v2['client_ordernum'] == $v) {
                    $flag = 1;
                    break;
                }
            }
            if ($flag == 0) {
                $temp = db("order o ")->field('o.id,o.client_ordernum')->where([
                    ['o.client_ordernum', '=', $v],
                    ['o.status', '=', 1],//99作废
                ])->find();
                $res = $this->orderOutgoService->cutPackageLabel($temp['id'], 1, '裁片');
                if ($res['code'] != 1) {
                    return $this->json(10, "此{$temp['client_ordernum']}单号还没分外发子工厂");
                }
            }
        }
        $list = $this->_waitDeliverCutPackageLabelGet($where);
        return $this->json(1, '', $list, count($list));
    }

    private function _waitDeliverCutPackageLabelGet($where)
    {
        return db("order_outgo_cpl ooc")
            ->field('ooc.*,o.client_ordernum,o.quantity
            ,f.name as factory_name,f.type
            ,g.name as group_name,g.mobile,g.address,g.unit_workshop
            ,oot.cut_packages_remark
            ,sum(os.shicai_count) as shicai_count_sum
            ')
            ->join('order o ', 'o.id=ooc.order_id', 'left')
            ->join('factory f', 'f.id=o.factory_id', 'left')
            ->join('order_outgo oot', 'oot.order_id=o.id', 'left')
            ->join('group g', 'oot.group_id=g.id', 'left')
            ->join('order_size os ', 'o.id=os.order_id', 'left')
            ->where($where)->group('ooc.id')->select();
    }

    /**
     * 外发管理》节点进度》待发货 --确认发货--实际操作
     * @date 2021/12/10
     * @author zhuguosen 905502314@qq.com
     */
    public function sendConfirm()
    {
        //1,参数处理
        $info = $this->request->param('info/s', '');
        if ($info == '') {
            return $this->json(10, '没有数据', []);
        }
        $info = explode(',', $info);
        $param = [];
        $order_ids = [];
        foreach ($info as $k => $v) {
            $temp = explode('/', $v);
            $param[] = $temp;
            $order_ids[] = $temp[0];
        }
        // 启动事务
        Db::startTrans();
        try {
            //2,业务->标识发货的包 order_outgo_cpl表修改
            foreach ($param as $k => $v) {
                $where = [
                    'ooc.order_id' => $v[0],
                    'ooc.num_0' => $v[2],
                    'ooc.num_1' => $v[3],
                    'ooc.status_send' => 0,
                ];
                $temp = db("order_outgo_cpl ooc")
                    ->where($where)->update([
                        'ooc.status' => 0,
                        'ooc.status_send' => 1,
                        'ooc.update_time' => time(),
                    ]);
            }
            //3,业务->order_outgo表的修改
            $res = $this->orderOutgoService->sendConfirm($order_ids);
            //4,业务log->wx_order_outgo_action_log表记录
            $temp = $this->orderOutgoService->action_log([
                'type' => 'waitDeliver_sendConfirm',
                'param' => $param,
            ]);
            //5,成本->暂无
            //6,财务->委外对帐--数据记录
            $temp = $this->orderOutgoService->order_status_0([
                'type' => 'waitDeliver_sendConfirm',
                'param' => [
                    'param' => $param,
                    'order_ids' => $order_ids,
                ],
            ]);
            if ($temp == false) {
                Db::rollback();
                return $this->json(100, '发货失败');
            }
            //7,经验->暂无
            Db::commit();
            return $this->json(1, '发货成功');
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->json(13, '发货失败');
        }
    }

    /**
     * 外发管理》节点进度》车缝中
     * @date 2021/11/24
     * @author zhuguosen 905502314@qq.com
     */
    public function sewing()
    {
        if ($this->request->isAjax() || $this->request->param('export/d', 0) || $this->request->param('ajaxflag/d', 0) == 1) {
            $page = $this->request->param('page/d', 1);
            $limit = $this->request->param('limit/d', 20);
            $nodeData = $this->nodeSetAndView('sewing');
            if ($nodeData['code'] > 0) {
                return json($nodeData);
            }
            list($where, $whereRaw0) = $this->_where_sewing();
            $order = "oot.update_time desc";
            $list = db('order o')
                ->field("ft.type as ft_type,ft.name as ft_name,o.id,o.client_ordernum ,o.shipment_time,o.quantity,o.sku,o.type
                ,o.factory_id
                ,s.pic,s.ori_pic
                ,sum(os.shicai_count) sum_shicai_count 
                ,g.mobile,g.name as g_name,g.id as g_id
                ,oot.sewing_return_time
                ,oot.time_send_0
                ")
                ->join('order_outgo oot', "o.id=oot.order_id", 'left')
                ->join('factory ft', "ft.id=o.factory_id", 'left')
                ->join('sku s', "o.sku=s.sku", 'left')
                ->join('order_size os ', 'os.order_id=o.id', 'left')
                ->join('wx_group g', 'oot.group_id=g.id', 'left')
                ->where($where)
                ->whereRaw($whereRaw0)
                ->page($page)->limit($limit)->orderRaw($order)
                ->group('o.id')->select();
            $count = db('order o')
                ->join('order_outgo oot', "o.id=oot.order_id", 'left')
                ->join('factory ft', "ft.id=o.factory_id", 'left')
                ->join('sku s', "o.sku=s.sku", 'left')
                ->join('order_size os ', 'os.order_id=o.id', 'left')
                ->join('wx_group g', 'oot.group_id=g.id', 'left')
                ->where($where)
                ->whereRaw($whereRaw0)
                ->group('o.id')->count();
            foreach ($list as $k => $v) {
                $list[$k]['groupList'] = getGroupKV($v['factory_id']);
                $list[$k]['type_txt'] = arrayGet(config('mimo.order_type'), $v['type'], '');
                $list[$k]['pic_res'] = trim($v['ori_pic']) == '' ? $v['pic'] : $v['ori_pic'];
                $list[$k]['status_txt'] = '车缝中';
                $temp = $v['shipment_time'] - time();
                if ($temp < 2 * 24 * 3600 && $temp > 0) {
                    $list[$k]['status_txt'] = '预警';
                }
                if ($temp < 0) {
                    $list[$k]['status_txt'] = '已超期';
                }
                $list[$k]['shipment_time'] = intval($list[$k]['shipment_time']) <= 0 ? '' : date('m-d', $list[$k]['shipment_time']);//出货时间
                $list[$k]['sewing_return_time_date'] = intval($list[$k]['sewing_return_time']) <= 0 ? '' : date('m-d', $list[$k]['sewing_return_time']);//回货时间
                //耗时天数
                $list[$k]['consume_day'] = $this->_consume_day($v['time_send_0']);
            }
            $list_last = [];
            foreach ($list as $k => $v) {
                $list_last["_{$v['client_ordernum']}"] = $v;
            }
            //获取各状态统计数据
            $status_sum = $this->_status_sum_sewing($where, $whereRaw0);
            $result = [
                'code' => 0,
                'msg' => '',
                'data' => $list_last,
                'pageInfo' => [
                    'count' => $count,
                    'maxPage' => ceil($count / $limit),
                ],
                'txt' => [
                ],
                'status_sum' => $status_sum,
            ];
            return json($result);
        }
        $assign = [
            'factoryAll' => $this->_factorylist([
                'ft_type' => 1,
            ], true),
            'client_ordernum' => $this->request->param('client_ordernum/s', ''),
            'sku' => $this->request->param('sku/s', ''),
        ];
        return $this->assign($assign)->fetch();
    }

    private function _deal_order_size_list($order_size_list)
    {
        $res = [];
        $list = explode(';', $order_size_list);
        foreach ($list as $k => $v) {
            $temp = explode(',', $v);
            $res[] = [
                'mid' => $temp[0],
                'size_name' => $temp[1],
                'order_count' => $temp[2],
                'shicai_count' => $temp[3],
                'jiaohuo_count' => $temp[4],
                'jiaohuo_tail_count' => $temp[5],
                'delivery_count' => $temp[6],
                'daohuo_count' => $temp[7],
                'store_count' => $temp[8],
            ];
        }
        return $res;
    }

    /**
     * 耗时天数
     * @param int $time
     * @author zhuguosen 905502314@qq.com
     * @date 2022/5/7
     */
    private function _consume_day($time = 0)
    {
        $day = floor(($this->now - $time) / (24 * 3600));
        return $day;
    }

    private function _ft_group_list($ft_group_list)
    {
        if (trim($ft_group_list) == '') {
            return [];
        }
        $res = [];
        $temp = explode(';', $ft_group_list);
        foreach ($temp as $k => $v) {
            $temp2 = explode(',', $v);
//            $res[] = [
//                'id' => $temp2[0],
//                'name' => $temp2[1],
//            ];
            $res[$temp2[0]] = $temp2[1];
        }
        return $res;
    }

    private function _status_sum_sewing($where, $whereRaw0)
    {
        $info_0 = db('order o')
            ->field('count(o.id) as count,sum(o.quantity) as sum_quantity
                ')
            ->join('order_outgo oot', "o.id=oot.order_id", 'left')
            ->join('factory ft', "ft.id=o.factory_id", 'left')
            ->join('sku s', "o.sku=s.sku", 'left')
//            ->join('order_size osize ', 'osize.order_id=o.id', 'left')
            ->join('wx_group g', 'oot.group_id=g.id', 'left')
            ->where($where)
            ->whereRaw($whereRaw0 . " and o.shipment_time >=  2 * 24 * 3600 + UNIX_TIMESTAMP(NOW()) ")
            ->find();
        $info_1 = db('order o')
            ->field('count(o.id) as count,sum(o.quantity) as sum_quantity
                ')
            ->join('order_outgo oot', "o.id=oot.order_id", 'left')
            ->join('factory ft', "ft.id=o.factory_id", 'left')
            ->join('sku s', "o.sku=s.sku", 'left')
//            ->join('order_size osize ', 'osize.order_id=o.id', 'left')
            ->join('wx_group g', 'oot.group_id=g.id', 'left')
            ->where($where)
            ->whereRaw($whereRaw0 . " and o.shipment_time   <  2 * 24 * 3600+UNIX_TIMESTAMP(NOW()) and o.shipment_time > UNIX_TIMESTAMP(NOW())  ")
            ->find();
        $info_2 = db('order o')
            ->field('count(o.id) as count,sum(o.quantity) as sum_quantity
                ')
            ->join('order_outgo oot', "o.id=oot.order_id", 'left')
            ->join('factory ft', "ft.id=o.factory_id", 'left')
            ->join('sku s', "o.sku=s.sku", 'left')
//            ->join('order_size osize ', 'osize.order_id=o.id', 'left')
            ->join('wx_group g', 'oot.group_id=g.id', 'left')
            ->where($where)
            ->whereRaw($whereRaw0 . " and o.shipment_time  < UNIX_TIMESTAMP(NOW()) ")
            ->find();
        $res = [];
        $res[] = [
            'name' => '车缝中',
            'count' => $info_0['count'],
            'sum_quantity' => floatval($info_0['sum_quantity']),
        ];
        $res[] = [
            'name' => '预警',
            'count' => $info_1['count'],
            'sum_quantity' => floatval($info_1['sum_quantity']),
        ];
        $res[] = [
            'name' => '已超期',
            'count' => $info_2['count'],
            'sum_quantity' => floatval($info_2['sum_quantity']),
        ];
        return $res;
    }

    private function _where_sewing()
    {
        $where = [
            ['ft.type', '=', 1],
        ];
        //订单加一级
        order_level($where, 'o.');
        $whereRaw0 = ' 1=1 ';
        $where[] = ["oot.status", "=", 200];
        $clientOrdernum = $this->request->param('client_ordernum/s', '');
        $sku = $this->request->param('sku/s', '');
        $shipment_date_range = $this->request->param('shipment_date_range/s', '');
        $sewing_return_date_range = $this->request->param('sewing_return_date_range/s', '');
        $time_send_0_range = $this->request->param('time_send_0_range/s', '');
        $factory_parent = intval($this->request->param('factory_parent', 0));
        $factory_child = intval($this->request->param('factory_child', 0));
        $status_temp = intval($this->request->param('status_temp', 0));
        $order_type = intval($this->request->param('order_type/d', 0));
        $consume_day = intval($this->request->param('consume_day/d', 0));
        $factory_all = trim($this->request->param('factory_all'));
        if ($clientOrdernum == '') {
            $where[] = ['o.status', '<>', 99];
        }
        if ($clientOrdernum != '') {
            $where[] = ['o.client_ordernum', 'like', "%" . $clientOrdernum . "%"];
        }
        if ($sku != '') {
            $where[] = ['o.sku', 'like', "%" . $sku . "%"];
        }
        if ($shipment_date_range != '') {
            list($startTime, $endTime) = array_map('strtotime', explode('~', $shipment_date_range));
            $where[] = ['o.shipment_time', 'between', [$startTime, $endTime + 86399]];
        }
        if ($sewing_return_date_range != '') {
            list($startTime, $endTime) = array_map('strtotime', explode('~', $sewing_return_date_range));
            $where[] = ['oot.sewing_return_time', 'between', [$startTime, $endTime + 86399]];
        }
        if ($time_send_0_range != '') {
            list($startTime, $endTime) = array_map('strtotime', explode('~', $time_send_0_range));
            $where[] = ['oot.time_send_0', 'between', [$startTime, $endTime + 86399]];
        }
        if ($factory_parent > 0) {
            $where[] = ['o.factory_id', '=', $factory_parent];
        }
        if ($factory_child > 0) {
            $where[] = ['oot.group_id', '=', $factory_child];
        }
        switch ($status_temp) {//容易出现，注意下。 [Err] 1690 - BIGINT UNSIGNED value is out of range in '(`020mimo_com_local`.`o`.`shipment_time` - <cache>(unix_timestamp(now())))'
            case 1://车缝中  o.shipment_time - ( UNIX_TIMESTAMP(NOW()) )  < 0  容易出错 [Err] 1690 - BIGINT UNSIGNED
                $whereRaw0 = ' o.shipment_time >=  2 * 24 * 3600 + UNIX_TIMESTAMP(NOW()) ';
                break;
            case 2://预警
                $whereRaw0 = 'o.shipment_time   <  2 * 24 * 3600+UNIX_TIMESTAMP(NOW()) and o.shipment_time > UNIX_TIMESTAMP(NOW()) ';
                break;
            case 3://已超期
                $whereRaw0 = ' o.shipment_time  < UNIX_TIMESTAMP(NOW())';
                break;
        }
        if ($factory_all != '') {
            $factory_all_array = explode(',', $factory_all);
            foreach ($factory_all_array as $k => $v) {
                $factory_all_array[$k] = intval($v);
            }
            $where[] = ['oot.group_id', 'in', $factory_all_array];
        }
        if ($order_type > 0) {
            switch ($order_type) {
                case 1://新单
                    $where[] = ['o.is_new', '=', 1];
                    break;
                case 2://返单
                    $where[] = ['o.is_new', '=', 0];
                    break;
            }
        }
        if ($consume_day > 0) {
            switch ($consume_day) {
                case 1:
                case 2:
                case 3:
                case 4:
                case 5:
                    $consume_day--;
                    $temp2 = $this->now - (($consume_day + 1) * 24 * 3600);
                    $temp = $this->now - ($consume_day * 24 * 3600);
                    $where[] = ['oot.time_send_0', '<=', $temp];
                    $where[] = ['oot.time_send_0', '>', $temp2];
                    break;
                case 104://4天以上
                    $temp = $this->now - (5 * 24 * 3600);
                    $where[] = ['oot.time_send_0', '<=', $temp];
                    break;
            }
        }
        return [$where, $whereRaw0];
    }

    /**
     * 在车缝中的订单修改 分组
     * @author zhuguosen 905502314@qq.com
     * @date 2022/5/7
     */
    public function sewing_change_group()
    {
        $param = [
            'order_id' => $this->request->param('order_id/d', 0),
            'group_id' => $this->request->param('group_id/d', 0),
        ];
        $orList = db('order_outgo_order')->where(['order_id' => $param['order_id']])->select();
        foreach ($orList as $k => $v) {
            if ($v['status'] >= 1120) {
                return $this->json(14, '此订单已审核了，不能修改分组');
            }
        }
        // 启动事务
        Db::startTrans();
        try {
            db('order_outgo')->where(['order_id' => $param['order_id']])->update([
                'group_id' => $param['group_id'],
            ]);
            db('order_outgo_action_log')->where(['order_id' => $param['order_id']])->update([
                'group_id' => $param['group_id'],
            ]);
            db('order_outgo_order')->where(['order_id' => $param['order_id']])->update([
                'factory_child_id' => $param['group_id'],
            ]);
            Db::commit();
            return $this->json(1, '成功');
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->json(13, '失败');
        }
    }

    /**
     * 确认回货 小页面
     * @date 2021/12/7
     * @author zhuguosen 905502314@qq.com
     */
    public function confirmReturnGoodsView()
    {
        $client_ordernum_all = $this->request->param('client_ordernum_all', '');
        $client_ordernum_all = explode(',', $client_ordernum_all);
        $where = [
            ['o.client_ordernum', 'in', $client_ordernum_all],
            ['o.status', '=', 1],//99作废
        ];
        $list = db('order o')
            ->field('ft.type as ft_type,ft.name as ft_name,o.id,o.client_ordernum ,o.shipment_time,o.quantity,o.sku,o.type
                ,s.pic,s.ori_pic
                ,sum(om.shicai_count) sum_shicai_count 
                ,g.mobile
                ,oot.sew_save_data,oot.sew_return_material_flag')
            ->join('order_outgo oot', "o.id=oot.order_id", 'left')
            ->join('factory ft', "ft.id=o.factory_id", 'left')
            ->join('sku s', "o.sku=s.sku", 'left')
            ->join('order_material om ', 'om.order_id=o.id', 'left')
            ->join('wx_group g', 'oot.group_id=g.id', 'left')
            ->where($where)
            ->group('om.order_id')->select();

        foreach ($list as $k => $v) {
            $osList = (new OrderSizeService())->getListByOrderId($v['id'], 'mid,order_count,daohuo_count,shicai_count,jiaohuo_tail_count,delivery_count,jiaohuo_count,size_name,tail_stock_in_out,tail_defective');
            if (trim($v['sew_save_data']) != '') {
                $sew_save_data = unserialize($v['sew_save_data']);
                foreach ($osList as $k2 => $v2) {
                    $osList[$k2]['return_goods_num'] = $sew_save_data['return_goods_num'][$v2['mid']];
                }
            }
            foreach ($osList as $k2 => $v2) {
                $osList[$k2]['return_goods_num'] = $osList[$k2]['return_goods_num'] ?? 0;
                $osList[$k2]['owe'] = $v2['shicai_count'] - intval($osList[$k2]['return_goods_num'] ?? 0);
            }
            $list[$k]['osList'] = $osList;
        }
        $list_last = [];
        foreach ($list as $k => $v) {
            $list_last["_{$v['client_ordernum']}"] = $v;
        }
        $assign = [
            'list' => $list_last,
        ];
        return $this->assign($assign)->fetch();
    }

    /**
     * 确认回货
     * @date 2021/11/25
     * @author zhuguosen 905502314@qq.com
     */
    public function confirmReturnGoods()
    {
        //1,参数处理
        $param = $this->request->param();
        //2,wx_order_outgo数据修改
        switch ($param['type_name']) {
            case 'sewing':
                $client_ordernum_all = [];
                foreach ($param['return_goods_num'] as $k => $v) {
                    $client_ordernum_all[] = $k;
                }
                $order_list = db('order o')
                    ->field('o.id,o.client_ordernum')
                    ->where([
                        ['o.client_ordernum', 'in', $client_ordernum_all],
                        ['o.status', '=', 1],//99作废
                    ])->select();
                $param_all = [];
                foreach ($order_list as $k => $v) {
                    $param_all[$k]['order_id'] = $v['id'];
                    $param_all[$k]['client_ordernum'] = $v['client_ordernum'];
                    $param_all[$k]['return_goods_num'] = $param['return_goods_num'][$v['client_ordernum']];
                    $param_all[$k]['owe'] = $param['owe'][$v['client_ordernum']];
                    $param_all[$k]['sew_return_material_flag'] = $param['sew_return_material_flag'][$v['client_ordernum']];
                }
                Db::startTrans();
                try {
                    //2.1,业务->跳过系统-车间工序
                    $res1 = $this->_confirmReturnGoods_real_chejian($param_all);
                    if ($res1 == false) {
                        Db::rollback();
                        return $this->json(11, '设置失败');
                    }
                    //2.2,业务->新系统-数据修改
                    $res2 = $this->_confirmReturnGoods_real($param_all);
                    if ($res2 == false) {
                        Db::rollback();
                        return $this->json(12, '设置失败', [$res2, $param_all]);
                    }
                    Db::commit();
                    return $this->json(1, '');
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    return $this->json(13, '设置失败');
                }
                break;
            case 'sewing_save':
                $client_ordernum_all = [];
                foreach ($param['return_goods_num'] as $k => $v) {
                    $client_ordernum_all[] = $k;
                }
                $order_list = db('order o')
                    ->field('o.id,o.client_ordernum')
                    ->where([
                        ['o.client_ordernum', 'in', $client_ordernum_all],
                        ['o.status', '=', 1],//99作废
                    ])->select();
                $param_all = [];
                foreach ($order_list as $k => $v) {
                    $param_all[$k]['order_id'] = $v['id'];
                    $param_all[$k]['client_ordernum'] = $v['client_ordernum'];
                    $param_all[$k]['return_goods_num'] = $param['return_goods_num'][$v['client_ordernum']];
                    $param_all[$k]['owe'] = $param['owe'][$v['client_ordernum']];
                    $param_all[$k]['sew_return_material_flag'] = $param['sew_return_material_flag'][$v['client_ordernum']];
                }
                Db::startTrans();
                try {
                    //2.2,业务->新系统-数据修改
                    $res2 = $this->_confirmReturnGoods_real_save($param_all);
                    if ($res2 == false) {
                        Db::rollback();
                        return $this->json(12, '设置失败', [$res2, $param_all]);
                    }
                    Db::commit();
                    return $this->json(1, '');
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    return $this->json(13, '设置失败');
                }
                break;
            case 'outgoTail':
                $param['client_ordernum_all'] = explode(',', $param['client_ordernum_all']);
                $order_list = db('order o')
                    ->field('o.id,o.client_ordernum')
                    ->where([
                        ['o.client_ordernum', 'in', $param['client_ordernum_all']],
                        ['o.status', 'in', [0, 1]],//99作废
                    ])->select();
                $param_all = [];
                foreach ($order_list as $k => $v) {
                    $param_all[$k]['order_id'] = $v['id'];
                    $param_all[$k]['client_ordernum'] = $v['client_ordernum'];
                    foreach ($param['client_ordernum_all'] as $k2 => $v2) {
                        if ($v2 == $v['client_ordernum']) {
                            $param_all[$k]['sew_return_goods_num'] = $param['sew_return_goods_num'][$k2];
                            $param_all[$k]['sew_owe'] = $param['sew_owe'][$k2];
                            $param_all[$k]['sew_return_material_flag'] = $param['sew_return_material_flag'][$k2];
                            break;
                        }
                    }
                }
                Db::startTrans();
                try {
                    //2.2,业务->新系统-数据修改
                    $res2 = $this->_confirmReturnGoods_real_outgoTail($param_all);
                    if ($res2 == false) {
                        Db::rollback();
                        return $this->json(12, '设置失败');
                    }
                    Db::commit();
                    return $this->json(1, '');
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    return $this->json(13, '设置失败');
                }
                break;
            case 'finishReturn':
                $param['client_ordernum_all'] = explode(',', $param['client_ordernum_all']);
                $order_list = db('order o')
                    ->field('o.id,o.client_ordernum')
                    ->where([
                        ['o.client_ordernum', 'in', $param['client_ordernum_all']],
                        ['o.status', 'in', [0, 1, 2]],//99作废
                    ])->select();
                $param_all = [];
                foreach ($order_list as $k => $v) {
                    $param_all[$k]['order_id'] = $v['id'];
                    $param_all[$k]['client_ordernum'] = $v['client_ordernum'];
                    foreach ($param['client_ordernum_all'] as $k2 => $v2) {
                        if ($v2 == $v['client_ordernum']) {
                            $param_all[$k]['sew_return_goods_num'] = $param['sew_return_goods_num'][$k2];
                            $param_all[$k]['sew_owe'] = $param['sew_owe'][$k2];
                            $param_all[$k]['sew_return_material_flag'] = $param['sew_return_material_flag'][$k2];
                            break;
                        }
                    }
                }
                Db::startTrans();
                try {
                    //2.2,业务->新系统-数据修改
                    $res2 = $this->_confirmReturnGoods_real_finishReturn($param_all);
                    if ($res2 == false) {
                        Db::rollback();
                        return $this->json(12, '设置失败');
                    }
                    Db::commit();
                    return $this->json(1, '');
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    return $this->json(13, '设置失败', [$e->getCode(), $e->getMessage(), $e->getFile(), $e->getLine()]);
                }
                break;
            default:
                return $this->json(1000, '设置失败');
                break;
        }
    }

    //order_outgo wx_order_size  wx_order_outgo_action_log表修改
    private function _confirmReturnGoods_real_save($param_all)
    {
        foreach ($param_all as $k => $v) {
            //1,order_outgo表修改
            $sew_return_goods_num = 0;
            $sew_owe = 0;
            foreach ($v['return_goods_num'] as $k2 => $v2) {
                $sew_return_goods_num += $v2;
            }
            foreach ($v['owe'] as $k2 => $v2) {
                $sew_owe += $v2;
            }
            $temp = db('order_outgo oot')->where([
                ['oot.order_id', '=', $v['order_id']]
            ])->update([
                'sew_return_goods_num' => $sew_return_goods_num,
                'sew_owe' => $sew_owe,
                'sew_return_material_flag' => $v['sew_return_material_flag'],
                'sew_save_data' => serialize([
                    'return_goods_num' => $v['return_goods_num'],
                    'owe' => $v['owe'],
                ]),
                'update_time' => time(),
            ]);
            if ($temp == 0) {
                return false;
            }
//            //1.1,业务order_outgo_batch表的回货记录
//            $temp = $this->orderOutgoService->order_outgo_batch_return('sewing', $v, $sew_return_goods_num, $sew_owe, $v['sew_return_material_flag']);
//            if ($temp != 1) {
//                return false;
//            }
            //2,业务log->wx_order_outgo_action_log表修改
            //3,业务->wx_order_size表修改
            foreach ($v['return_goods_num'] as $k2 => $v2) {
                $temp2 = db('order_size ose')->where([
                    ['ose.order_id', '=', $v['order_id']],
                    ['ose.mid', '=', intval($k2)],
                ])->update([
                    'jiaohuo_count' => intval($v2),
                    'update_time' => time(),
                ]);
                if ($temp2 == 0) {
                    return false;
                }
            }
            //5,成本->暂无
            //6,财务->委外对帐--数据记录
            //7,经验->暂无
        }
        return true;
    }

    //order_outgo wx_order_size  wx_order_outgo_action_log表修改
    private function _confirmReturnGoods_real($param_all)
    {
        foreach ($param_all as $k => $v) {
            //1,order_outgo表修改
            $sew_return_goods_num = 0;
            $sew_owe = 0;
            foreach ($v['return_goods_num'] as $k2 => $v2) {
                $sew_return_goods_num += $v2;
            }
            foreach ($v['owe'] as $k2 => $v2) {
                $sew_owe += $v2;
            }
            $temp = db('order_outgo oot')->where([
                ['oot.order_id', '=', $v['order_id']]
            ])->update([
                'status' => 300,
                'status_after_return_num' => ['inc', 1],
                'sew_return_goods_num' => $sew_return_goods_num,
                'sew_owe' => $sew_owe,
                'sew_return_material_flag' => $v['sew_return_material_flag'],
                'admin_id_return_0' => ADMIN_ID,
                'time_return_0' => time(),
                'update_time' => time(),
            ]);
            if ($temp == 0) {
                return false;
            }
            //2,业务log->wx_order_outgo_action_log表修改
            $temp = $this->orderOutgoService->action_log([
                'type' => 'sewing_confirmReturnGoods',
                'param' => $v,
            ]);
            if ($temp == false) {
                return false;
            }
            //3,业务->wx_order_size表修改
            foreach ($v['return_goods_num'] as $k2 => $v2) {
                $temp2 = db('order_size ose')->where([
                    ['ose.order_id', '=', $v['order_id']],
                    ['ose.mid', '=', intval($k2)],
                ])->update([
                    'jiaohuo_count' => intval($v2),
                    'update_time' => time(),
                ]);
                if ($temp2 == 0) {
                    return false;
                }
            }
            //5,成本->暂无
            //6,财务->委外对帐--数据记录
            $temp = $this->orderOutgoService->order_status_0([
                'type' => 'sewing_confirmReturnGoods',
                'param' => $v,
            ]);
            if ($temp == false) {
                return false;
            }
            //7,经验->暂无
        }
        return true;
    }

    //order_outgo wx_order_size  wx_order_outgo_action_log表修改
    private function _confirmReturnGoods_real_outgoTail($param_all)
    {
        foreach ($param_all as $k => $v) {
            //1,业务->order_outgo表修改
            $temp = db('order_outgo oot')->where([
                ['oot.order_id', '=', $v['order_id']]
            ])->update([
                'status' => 300,
                'status_after_return_num' => ['inc', 1],
                'sew_return_goods_num' => $v['sew_return_goods_num'],
                'sew_owe' => $v['sew_owe'],
                'sew_return_material_flag' => $v['sew_return_material_flag'],
                'admin_id_return_2' => ADMIN_ID,
                'time_return_2' => time(),
                'update_time' => time(),
            ]);
            if ($temp == 0) {
                return false;
            }
            //1.1,业务order_outgo_batch表的回货记录
            $temp = $this->orderOutgoService->order_outgo_batch_return('outgoTail', $v, $v['sew_return_goods_num'], $v['sew_owe'], $v['sew_return_material_flag']);
            if ($temp != 1) {
                return false;
            }
            //2,业务log->wx_order_outgo_action_log表修改
            $temp = $this->orderOutgoService->action_log([
                'type' => 'outgoTail_confirmReturnGoods',
                'param' => $v,
            ]);
            if ($temp == false) {
                return false;
            }
            //5,成本->暂无
            //6,财务->委外对帐--数据记录
            $temp = $this->orderOutgoService->order_status_0([
                'type' => 'outgoTail_confirmReturnGoods',
                'param' => $v,
            ]);
            if ($temp == false) {
                return false;
            }
            //7,经验->暂无
        }
        return true;
    }

    //order_outgo wx_order_size  wx_order_outgo_action_log表修改
    private function _confirmReturnGoods_real_finishReturn($param_all)
    {
        foreach ($param_all as $k => $v) {
            //1,业务->order_outgo表修改
            $temp = db('order_outgo oot')->where([
                ['oot.order_id', '=', $v['order_id']]
            ])->update([
                'status' => 300,
                'status_after_return_num' => ['inc', 1],
                'sew_return_goods_num' => $v['sew_return_goods_num'],
                'sew_owe' => $v['sew_owe'],
                'sew_return_material_flag' => $v['sew_return_material_flag'],
                'admin_id_return_1' => ADMIN_ID,
                'time_return_1' => time(),
                'update_time' => time(),
            ]);
            if ($temp == 0) {
                return false;
            }
            //1.1,业务order_outgo_batch表的回货记录
            $temp = $this->orderOutgoService->order_outgo_batch_return('finishReturn', $v, $v['sew_return_goods_num'], $v['sew_owe'], $v['sew_return_material_flag']);
            if ($temp != 1) {
                return false;
            }
            //2,业务log->wx_order_outgo_action_log表修改
            $temp = $this->orderOutgoService->action_log([
                'type' => 'finishReturn_confirmReturnGoods',
                'param' => $v,
            ]);
            if ($temp == false) {
                return false;
            }
            //5,成本->暂无
            //6,财务->暂无
            //7,经验->暂无
        }
        return true;
    }

    private function _confirmReturnGoods_real_chejian($param_all)
    {
        foreach ($param_all as $k => $v) {
            $temp = db('order')->where([
                ["id", '=', $v['order_id']],
                ["chejian_status", '=', 0],
            ])->update([
                'chejian_status' => 1,
                'chejian_over_time' => time(),
            ]);
            if ($temp == 0) {
                return false;
            }
            $this->addOrderLog($v['order_id'], $v['client_ordernum'], "车间完成-委外管理");
        }
        return true;
    }

    private function _confirmReturnGoods_real_old($param_all)
    {
        foreach ($param_all as $k => $v) {
            $temp = db('order_outgo oot')->where([
                ['oot.order_id', '=', $v['order_id']]
            ])->update([
                'status' => 300,
                'status_after_return_num' => ['inc', 1],
                'sew_return_goods_num' => $v['sew_return_goods_num'],
                'sew_owe' => $v['sew_owe'],
                'sew_return_material_flag' => $v['sew_return_material_flag'],
                'update_time' => time(),
            ]);
            if ($temp == 0) {
                return false;
            }
        }
        return true;
    }

    /**
     * 外发管理》节点进度》后整中
     * @date 2021/11/25
     * @author zhuguosen 905502314@qq.com
     */
    public function afterFinishing()
    {
        if ($this->request->isAjax() || $this->request->param('export/d', 0) || $this->request->param('ajaxflag/d', 0) == 1) {
            $page = $this->request->param('page/d', 1);
            $limit = $this->request->param('limit/d', 20);
            $nodeData = $this->nodeSetAndView('afterFinishing');
            if ($nodeData['code'] > 0) {
                return json($nodeData);
            }
            list($where, $whereRaw0) = $this->_where_afterFinishing();
            $order = "oot.update_time desc";
            $list = db('order o')
                ->field("ft.type as ft_type,ft.name as ft_name,o.id,o.client_ordernum ,o.shipment_time,o.quantity,o.sku,o.type
                ,o.tail_status
                ,s.pic,s.ori_pic
                ,sum(osize.shicai_count) sum_shicai_count 
                ,g.mobile,g.name as g_name
                ,oot.time_return_0,oot.batch_status,oot.batch_num
                ,sk.available_count
                ")
                ->join('order_outgo oot', "o.id=oot.order_id", 'left')
                ->join('factory ft', "ft.id=o.factory_id", 'left')
                ->join('sku s', "o.sku=s.sku", 'left')
                ->join('order_size osize ', 'osize.order_id=o.id', 'left')
                ->join('wx_group g', 'oot.group_id=g.id', 'left')
                ->join('sku_stock sk', 'o.sku=sk.sku and sk.available_count>0 ', 'left')
                ->where($where)
                ->whereRaw($whereRaw0)
                ->page($page)->limit($limit)->orderRaw($order)
                ->group('o.id')->select();
            $count = db('order o')
                ->join('order_outgo oot', "o.id=oot.order_id", 'left')
                ->join('factory ft', "ft.id=o.factory_id", 'left')
                ->join('sku s', "o.sku=s.sku", 'left')
                ->join('order_size osize ', 'osize.order_id=o.id', 'left')
                ->join('wx_group g', 'oot.group_id=g.id', 'left')
                ->where($where)
                ->whereRaw($whereRaw0)
                ->group('o.id')->count();
            $orderSizeService = new OrderSizeService();
            foreach ($list as $k => $v) {
                $list[$k]['type_txt'] = arrayGet(config('mimo.order_type'), $v['type'], '');
                $list[$k]['pic_res'] = trim($v['ori_pic']) == '' ? $v['pic'] : $v['ori_pic'];
                $list[$k]['status_txt'] = '车缝中';
                $temp = $v['shipment_time'] - time();
                if ($temp < 2 * 24 * 3600 && $temp > 0) {
                    $list[$k]['status_txt'] = '预警';
                } else {
                    $list[$k]['status_txt'] = '已超期';
                }
                $list[$k]['shipment_time'] = intval($list[$k]['shipment_time']) <= 0 ? '' : date('m-d', $list[$k]['shipment_time']);//出货时间
                if (trim($list[$k]['g_name']) == '') {
                    $list[$k]['g_name'] = '--未分配--';
                }
                //耗时天数
                $list[$k]['consume_day'] = $this->_consume_day($v['time_return_0']);
                $list[$k]['available_count'] = intval($list[$k]['available_count']);
                //其它操作》库存录入要的格式细码数据
                $osList = $orderSizeService->getListByOrderId($v['id'], 'mid,order_count,daohuo_count,shicai_count,jiaohuo_tail_count,delivery_count,jiaohuo_count,size_name,tail_stock_in_out,tail_defective');
                $list[$k]['osJson'] = json_encode($osList);
                $otherStockList = db('sku_stock')->where(['sku' => $v['sku']])->where('client_ordernum', 'not in', [$v['client_ordernum']])
                    ->field('dress_line_code,size_name,sum(available_count) as available_count,sum(defective_count) as defective_count')->group("size_name")->select();
                $list[$k]['otherStockList_json'] = json_encode($otherStockList);
                $list[$k]['finishinfo'] = db('order_finish')->where(['order_id' => $v['id']])->find();
            }
            $list_last = [];
            foreach ($list as $k => $v) {
                $list_last["_{$v['client_ordernum']}"] = $v;
            }
            //获取各状态统计数据
            $status_sum = $this->_status_sum_sewing($where, $whereRaw0);
            $result = [
                'code' => 0,
                'msg' => '',
                'data' => $list_last,
                'pageInfo' => [
                    'count' => $count,
                    'maxPage' => ceil($count / $limit),
                ],
                'txt' => [
                ],
                'status_sum' => $status_sum,
            ];
            return json($result);
        }
        $assign = [
            'factoryAll' => $this->_factorylist([
                'ft_type' => 1,
            ], true),
            'client_ordernum' => $this->request->param('client_ordernum/s', ''),
            'sku' => $this->request->param('sku/s', ''),
        ];
        return $this->assign($assign)->fetch();
    }

    private function _where_afterFinishing()
    {
        $where = [
            ['ft.type', '=', 1],
        ];
        //订单加一级
        order_level($where, 'o.');
        $whereRaw0 = ' 1=1 ';
        $where[] = ["oot.status", "=", 300];
        $clientOrdernum = $this->request->param('client_ordernum/s', '');
        $sku = $this->request->param('sku/s', '');
        $factory_all = trim($this->request->param('factory_all'));
        $status_temp = intval($this->request->param('status_temp', 0));
        $consume_day = intval($this->request->param('consume_day/d', 0));
        $createDateRange = $this->request->param('create_date_range/s', '');
        $shipment_date_range = $this->request->param('shipment_date_range/s', '');
        $time_return_0_range = $this->request->param('time_return_0_range/s', '');
        if ($clientOrdernum == '') {
            $where[] = ['o.status', '<>', 99];
        }
        if ($clientOrdernum != '') {
            $where[] = ['o.client_ordernum', 'like', "%" . $clientOrdernum . "%"];
        }
        if ($sku != '') {
            $where[] = ['o.sku', 'like', "%" . $sku . "%"];
        }
        if ($factory_all != '') {
            $factory_all_array = explode(',', $factory_all);
            foreach ($factory_all_array as $k => $v) {
                $factory_all_array[$k] = intval($v);
            }
            $where[] = ['oot.group_id', 'in', $factory_all_array];
        }
        if ($createDateRange != '') {
            list($startTime, $endTime) = array_map('strtotime', explode('~', $createDateRange));
            $where[] = ['o.create_time', 'between', [$startTime, $endTime + 86399]];
        }
        if ($shipment_date_range != '') {
            list($startTime, $endTime) = array_map('strtotime', explode('~', $shipment_date_range));
            $where[] = ['o.shipment_time', 'between', [$startTime, $endTime + 86399]];
        }
        if ($time_return_0_range != '') {
            list($startTime, $endTime) = array_map('strtotime', explode('~', $time_return_0_range));
            $where[] = ['oot.time_return_0', 'between', [$startTime, $endTime + 86399]];
        }
        if ($consume_day > 0) {
            switch ($consume_day) {
                case 1:
                case 2:
                case 3:
                case 4:
                case 5:
                    $consume_day--;
                    $temp2 = $this->now - (($consume_day + 1) * 24 * 3600);
                    $temp = $this->now - ($consume_day * 24 * 3600);
                    $where[] = ['oot.time_return_0', '<=', $temp];
                    $where[] = ['oot.time_return_0', '>', $temp2];
                    break;
                case 104://4天以上
                    $temp = $this->now - (5 * 24 * 3600);
                    $where[] = ['oot.time_return_0', '<=', $temp];
                    break;
            }
        }
        switch ($status_temp) {//容易出现，注意下。 [Err] 1690 - BIGINT UNSIGNED value is out of range in '(`020mimo_com_local`.`o`.`shipment_time` - <cache>(unix_timestamp(now())))'
            case 1://车缝中  o.shipment_time - ( UNIX_TIMESTAMP(NOW()) )  < 0  容易出错 [Err] 1690 - BIGINT UNSIGNED
                $whereRaw0 = ' o.shipment_time >=  2 * 24 * 3600 + UNIX_TIMESTAMP(NOW()) ';
                break;
            case 2://预警
                $whereRaw0 = 'o.shipment_time   <  2 * 24 * 3600+UNIX_TIMESTAMP(NOW()) and o.shipment_time > UNIX_TIMESTAMP(NOW()) ';
                break;
            case 3://已超期
                $whereRaw0 = ' o.shipment_time  < UNIX_TIMESTAMP(NOW())';
                break;
        }
        return [$where, $whereRaw0];
    }

    /**
     * 返工计时
     * @date 2021/11/26
     * @author zhuguosen 905502314@qq.com
     */
    public function returnTime()
    {
        if ($this->request->isAjax() || $this->request->param('export/d', 0) || $this->request->param('ajaxflag/d', 0) == 1) {
            //1,参数处理
            $param = [
                'order_id' => $this->request->param('order_id/d', 0),
                'after_return_reason' => $this->request->param('after_return_reason/s', ''),
                'after_return_num' => $this->request->param('after_return_num/d', 0),
                'after_return_time' => floatval($this->request->param('after_return_time', 0)),
            ];
            if ($param['after_return_reason'] == '') {
                return $this->json(10, '请输入返工原因');
            }
            $info = db('order_outgo oot')
                ->where([
                    ['oot.order_id', '=', $param['order_id']],
                ])->find();
            if ($info['group_id'] == 0) {
                return $this->json(10, '请先设置分组');
            }
            Db::startTrans();
            try {
                //2,业务->修改表 wx_order_outgo
                $temp = db('order_outgo oot')
                    ->where([
                        ['oot.order_id', '=', $param['order_id']],
                    ])->update([
                        'update_time' => time(),
                        'after_return_reason' => $param['after_return_reason'],
                        'after_return_num' => $param['after_return_num'],
                        'after_return_time' => $param['after_return_time'],
                    ]);
                if ($temp != 1) {
                    Db::rollback();
                    return $this->json(12, '设置失败');
                }
                //3,业务log->wx_order_outgo_action_log表修改
                $temp = $this->orderOutgoService->action_log([
                    'type' => 'afterFinishing_returnTime',
                    'param' => $param,
                ]);
                if ($temp == false) {
                    Db::rollback();
                    return $this->json(14, '设置失败');
                }
                //5,成本->暂无
                //6,财务->wx_order_outgo_order 表修改
                if ($info['data_status'] == 0) {
                    $temp = $this->orderOutgoService->order_status_0([
                        'type' => 'afterFinishing_returnTime',
                        'param' => [
                            'order_id' => $param['order_id'],
                            'after_return_reason' => $param['after_return_reason'],
                            'after_return_num' => $param['after_return_num'],
                            'after_return_time' => $param['after_return_time'],
                        ],
                    ]);
                    if ($temp == false) {
                        Db::rollback();
                        return $this->json(15, '失败');
                    }
                }
                //7,经验->暂无
                Db::commit();
                return $this->json(1, '保存成功');
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return $this->json(13, '设置失败');
            }
        }
        //1,显示参数处理
        $order_id = $this->request->param('order_id/d', 0);
        $type = $this->request->param('type/s', '');
        $tabData = [];
        $tabData['menu'][] = [
            'title' => '返回计时',
            'url' => "mp/OutNodeProgress/returnTime?order_id={$order_id}&type={$type}",
        ];
        $tabData['menu'][] = [
            'title' => '外协尾部',
            'url' => "mp/OutNodeProgress/outTail?order_id={$order_id}&type={$type}",
        ];
        $tabData['menu'][] = [
            'title' => '委外设置',
            'url' => "mp/OutNodeProgress/unitSetReadonly?order_id={$order_id}&type={$type}",
        ];
        $tabData['current'] = url("mp/OutNodeProgress/returnTime?order_id={$order_id}&type={$type}");
        //10，查询 上次返工原因 与返工计时信息
        $info = db('order o')
            ->field('o.id,o.client_ordernum 
                ,g.unit_time_price
                ,oot.after_return_reason,oot.after_return_num,oot.after_return_time
                ')
            ->join('order_outgo oot', "o.id=oot.order_id", 'left')
            ->join('factory ft', "ft.id=o.factory_id", 'left')
            ->join('wx_group g', 'oot.group_id=g.id', 'left')
            ->where([
                ['o.id', '=', $order_id],
            ])->find();
        $assign = [
            'hisiTabData' => $tabData,
            'hisiTabType' => 3,
            'order_id' => $order_id,
            'client_ordernum' => $info['client_ordernum'],
            'unit_time_price' => $info['unit_time_price'],
            'after_return_reason' => $info['after_return_reason'],
            'after_return_num' => $info['after_return_num'],
            'after_return_time' => $info['after_return_time'],
            'type' => $type,
        ];
        return $this->assign($assign)->fetch();
    }

    /**
     * 外发管理》节点进度》后整中  外协尾部
     * @date 2021/11/26
     * @author zhuguosen 905502314@qq.com
     */
    public function outTail()
    {
        if ($this->request->isAjax() || $this->request->param('export/d', 0) || $this->request->param('ajaxflag/d', 0) == 1) {
            //1,参数处理
            $param = [
                'order_id' => $this->request->param('order_id/d', 0),
                'after_out_type' => $this->request->param('after_out_type/s', ''),
                'after_factory_id' => $this->request->param('after_factory_id/d', 0),
                'after_group_id' => floatval($this->request->param('after_group_id', 0)),
                'after_price' => floatval($this->request->param('after_price', 0)),
                'after_num' => intval($this->request->param('after_num', 0)),
            ];
            if ($param['after_out_type'] == '' && $param['after_group_id'] > 0) {
                return $this->json(10, '请输入委外类型 与 委外工厂');
            }
            if ($param['after_price'] <= 0 && $param['after_num'] <= 0) {
                return $this->json(11, '请输入委外单价(元) 与 委外数量(件)');
            }
            $after_out_type_array = explode(',', $param['after_out_type']);
            //1.2倍率信息查询
            $info = db('order o')
                ->field('o.id,o.client_ordernum ,o.order_price
             ,g.unit_tail,g.unti_manual,oot.group_id
                ')
                ->join('order_outgo oot', "o.id=oot.order_id", 'left')
                ->join('factory ft', "ft.id=o.factory_id", 'left')
                ->join('wx_group g', 'oot.group_id=g.id', 'left')
                ->where([
                    ['o.id', '=', $param['order_id']],
                ])->find();
            if ($info['group_id'] == 0) {
                return $this->json(10, '请先设置分组');
            }
            foreach ($after_out_type_array as $k => $v) {
                switch ($v) {
                    case 3:
                        if (floatval($info['unit_tail']) <= 0) {
                            return $this->json(10, '请先设置尾部倍率', $info);
                        }
                        break;
                    case 4:
                        if (floatval($info['unti_manual']) <= 0) {
                            return $this->json(10, '请先设置专机或手工倍率');
                        }
                        break;
                }
            }
            //2,修改表 wx_order_outgo
            $temp = db('order_outgo')
                ->where([
                    ['order_id', '=', $param['order_id']],
                    ['status', '=', 300],
                ])->update([
//                    'status' => 302,
                    'update_time' => time(),
                    'after_out_type' => $param['after_out_type'],
                    'after_factory_id' => $param['after_factory_id'],
                    'after_group_id' => $param['after_group_id'],
                    'after_price' => $param['after_price'],
                    'after_num' => $param['after_num'],
                ]);
            if ($temp == 1) {
                return $this->json(1, '保存成功');
            }
            return $this->json(11, '保存出错');
        }

        //1,显示参数处理
        $order_id = $this->request->param('order_id/d', 0);
        $type = $this->request->param('type/s', '');
        $tabData['menu'] = [];
        $tabData['menu'][] = [
            'title' => '返回计时',
            'url' => "mp/OutNodeProgress/returnTime?order_id={$order_id}&type={$type}",
        ];
        $tabData['menu'][] = [
            'title' => '外协尾部',
            'url' => "mp/OutNodeProgress/outTail?order_id={$order_id}&type={$type}",
        ];
        $tabData['menu'][] = [
            'title' => '委外设置',
            'url' => "mp/OutNodeProgress/unitSetReadonly?order_id={$order_id}&type={$type}",
        ];
        $tabData['current'] = url("mp/OutNodeProgress/outTail?order_id={$order_id}&type={$type}");
        //10，查询表
        $info = db('order o')
            ->field("o.id,o.client_ordernum ,o.order_price
            ,ft.name as ft_name,g.name as group_name ,ft.id as ft_id,g.id as group_id
            ,g2.name as after_group_name
             ,g2.unit_cutting,g2.unit_workshop,g2.unit_tail,g2.unti_manual,g2.unit_time_price
            ,oot.after_price,oot.after_num,oot.after_out_type,oot.after_factory_id,oot.after_group_id
            ,sum(os.jiaohuo_count) as sum_jiaohuo_count
                ")
            ->join('order_outgo oot', "o.id=oot.order_id", 'left')
            ->join('factory ft', "ft.id=o.factory_id", 'left')
            ->join('wx_group g', 'oot.group_id=g.id', 'left')
            ->join('wx_group g2', 'oot.after_group_id=g.id', 'left')
            ->join('order_size os', "o.id=os.order_id", 'left')
            ->where([
                ['o.id', '=', $order_id],
            ])->group('o.id')->find();
        $info['after_out_type_txt'] = '';
        $info['after_unit'] = 0;
        switch ($info['after_out_type']) {
            case '3':
                $info['after_out_type_txt'] = '尾部';
                $info['after_unit'] = $info['unit_tail'];
                break;
            case '4':
                $info['after_out_type_txt'] = '专机';
                $info['after_unit'] = $info['unti_manual'];
                break;
            case '3,4':
                $info['after_out_type_txt'] = '尾部,专机';
                $info['after_unit'] = $info['unit_tail'] > 0 ? $info['unit_tail'] : $info['unti_manual'];
                break;
        }
        //委外数量 after_num 默认为回货总数，支持修改
        $type != "readonly" && $info['after_num'] == 0 && $info['after_num'] = $info['sum_jiaohuo_count'];
        $assign = [
            'hisiTabData' => $tabData,
            'hisiTabType' => 3,
            'factorylist_tail' => $this->_factorylist_all_info([
                'ft_id' => $info['ft_id'],
                'ft_type' => 1,
                'group_id' => $info['group_id'],
                'after_out_type' => $info['after_out_type'],
                'after_factory_id' => $info['after_factory_id'],
                'after_group_id' => $info['after_group_id'],
                'out_type' => 3,
            ]),
            'factorylist_manual' => $this->_factorylist_all_info([
                'ft_id' => $info['ft_id'],
                'ft_type' => 1,
                'group_id' => $info['group_id'],
                'after_out_type' => $info['after_out_type'],
                'after_factory_id' => $info['after_factory_id'],
                'after_group_id' => $info['after_group_id'],
                'out_type' => 4,
            ]),
            'factorylist_all' => $this->_factorylist_all_info([
                'ft_id' => $info['ft_id'],
                'ft_type' => 1,
                'group_id' => $info['group_id'],
                'after_out_type' => $info['after_out_type'],
                'after_factory_id' => $info['after_factory_id'],
                'after_group_id' => $info['after_group_id'],
                'out_type' => '3,4',
            ]),
            'info' => $info,
            'type' => $type,
        ];
        return $this->assign($assign)->fetch();
    }

    private function _factorylist_all_info($param)
    {
        $where[] = ['ft.status', '=', 1];
        $where[] = ['g.status', '=', 1];
        $where[] = ['g.out_type', 'like', "%{$param['out_type']}%"];
        $factorylist = db('factory ft')
            ->field('ft.id as ft_id,ft.name as ft_name,ft.type as ft_type 
            ,g.id as group_id,g.name as group_name ,g.factory_id as group_factory_id
            ,g.unit_tail,g.unti_manual
            ')
            ->join('wx_group g', 'g.factory_id=ft.id', 'left')
            ->where($where)
            ->select();
        $result = [];
        foreach ($factorylist as $k => $v) {
            if (isset($result[$v['ft_id']])) {
                continue;
            }
            $result[$v['ft_id']]['ft_id'] = $v['ft_id'];
            $result[$v['ft_id']]['ft_name'] = $v['ft_name'];
            $result[$v['ft_id']]['ft_type'] = $v['ft_type'];
            $result[$v['ft_id']]['selected'] = 0;
            if (isset($param['ft_id'])) {
                $v['ft_id'] == $param['ft_id'] && $result[$v['ft_id']]['selected'] = 1;
            }
            foreach ($factorylist as $k2 => $v2) {
                if ($v2['group_factory_id'] == $v['ft_id']) {
                    $result[$v['ft_id']]['child'][$v2['group_id']]['group_id'] = $v2['group_id'];
                    $result[$v['ft_id']]['child'][$v2['group_id']]['group_name'] = $v2['group_name'];
                    $result[$v['ft_id']]['child'][$v2['group_id']]['unit_tail'] = $v2['unit_tail'];
                    $result[$v['ft_id']]['child'][$v2['group_id']]['unti_manual'] = $v2['unti_manual'];
                    $result[$v['ft_id']]['child'][$v2['group_id']]['unti_all_price'] = $v2['unit_tail'] > 0 ? $v2['unit_tail'] : $v2['unti_manual'];
                    $result[$v['ft_id']]['child'][$v2['group_id']]['selected'] = 0;
                    if (isset($param['group_id'])) {
                        $v2['group_id'] == $param['group_id'] && $result[$v['ft_id']]['child'][$v2['group_id']]['selected'] = 1;
                    }
                }
            }
        }
        return $result;
    }

    /**
     *  获取所有工厂信息
     *  $this->_factorylist([
     * 'ft_id' => $info['ft_id'],
     * 'ft_type' => 1,
     * 'group_id' => $info['group_id'],
     * ]),
     * @param $param
     * @date 2021/11/27
     * @return array
     * @author zhuguosen 905502314@qq.com
     */
    private function _factorylist($param, $xm_select = false)
    {
        $where = [];
        if (isset($param['ft_type'])) {
            $where[] = ['ft.type', '=', $param['ft_type']];
        }
        $where[] = ['ft.status', '=', 1];
        $where[] = ['g.status', '=', 1];
        $factorylist = db('factory ft')
            ->field('ft.id as ft_id,ft.name as ft_name,ft.type as ft_type 
            ,g.id as group_id,g.name as group_name ,g.factory_id as group_factory_id
            ')
            ->join('wx_group g', 'g.factory_id=ft.id', 'left')
            ->where($where)
            ->select();
        $result = [];
        foreach ($factorylist as $k => $v) {
            if (isset($result[$v['ft_id']])) {
                continue;
            }
            $result[$v['ft_id']]['ft_id'] = $v['ft_id'];
            $result[$v['ft_id']]['ft_name'] = $v['ft_name'];
            $result[$v['ft_id']]['ft_type'] = $v['ft_type'];
            $result[$v['ft_id']]['selected'] = 0;
            if (isset($param['ft_id'])) {
                $v['ft_id'] == $param['ft_id'] && $result[$v['ft_id']]['selected'] = 1;
            }
            foreach ($factorylist as $k2 => $v2) {
                if ($v2['group_factory_id'] == $v['ft_id']) {
                    $result[$v['ft_id']]['child'][$v2['group_id']]['group_id'] = $v2['group_id'];
                    $result[$v['ft_id']]['child'][$v2['group_id']]['group_name'] = $v2['group_name'];
                    $result[$v['ft_id']]['child'][$v2['group_id']]['selected'] = 0;
                    if (isset($param['group_id'])) {
                        $v2['group_id'] == $param['group_id'] && $result[$v['ft_id']]['child'][$v2['group_id']]['selected'] = 1;
                    }
                }
            }
        }
        if ($xm_select == true) {
            $factoryAll = [];
            foreach ($result as $k => $v) {
                $temp = [
                    'name' => $v['ft_name'],
                    'value' => -$v['ft_id'],
                    'children' => [],
                ];
                if (count($v['child']) > 0) {
                    foreach ($v['child'] as $k2 => $v2) {
                        $temp['children'][] = [
                            'name' => $v2['group_name'],
                            'value' => $v2['group_id'],
                        ];
                    }
                }
                $factoryAll[] = $temp;
            }
            return $factoryAll;
        }
        return $result;
    }

    /**
     * 外发管理》节点进度》后整中  发起外协
     * @date 2021/11/29
     * @author zhuguosen 905502314@qq.com
     */
    public function confirmOutTail()
    {
        $param = [
            'type' => $this->request->param('type/s', 0),
            'client_ordernum_all' => $this->request->param('client_ordernum_all/s', ''),
        ];
        if ($param['client_ordernum_all'] == '') {
            return $this->json(10, '请转入要外协的订单号');
        }
        $param['client_ordernum_all'] = explode(',', $param['client_ordernum_all']);
        switch ($param['type']) {
            case 'select'://查询所有要外协的订单
                $list = db('order o')
                    ->field('o.id,o.client_ordernum ,o.order_price
            ,ft.name as ft_name,g.name as group_name ,ft.id as ft_id,g.id as group_id
            ,oot.after_price,oot.after_num,oot.after_out_type,oot.after_factory_id,oot.after_group_id
            ,oot.status,oot.batch_status
                ')
                    ->join('order_outgo oot', "o.id=oot.order_id", 'left')
                    ->join('factory ft', "ft.id=o.factory_id", 'left')
                    ->join('wx_group g', 'oot.group_id=g.id', 'left')
                    ->where([
                        ['o.client_ordernum', 'in', $param['client_ordernum_all']],
                        ['o.status', 'in', [0, 1]],//99作废
                    ])->select();
                $can_flag = 1;
                foreach ($list as $k => $v) {
                    if ($v['status'] == 300 && $v['batch_status'] == 0) {
                        $can_flag = 0;
                        return $this->json(0, '订单没全部回货完成，不能外协');
                        break;
                    }
                    switch ($v['after_out_type']) {
                        case '3':
                            $list[$k]['after_out_type_txt'] = '尾部';
                            break;
                        case '4':
                            $list[$k]['after_out_type_txt'] = '专机';
                            break;
                        case '3,4':
                            $list[$k]['after_out_type_txt'] = '尾部,专机';
                            break;
                    }
                }
                foreach ($list as $k => $v) {
                    if ($v['after_price'] <= 0 || $v['after_num'] <= 0) {
                        return $this->json(11, "单号：{$v['client_ordernum']}，请先设置委外单价(元) 与 委外数量(件)");
                    }
                }
                return $this->json(1, '', $list);
                break;
            case 'confirm':
                // 启动事务
                Db::startTrans();
                try {
                    //2,业务->order_outgo表修改
                    $temp = db('order o')
                        ->join('order_outgo oot', "o.id=oot.order_id", 'left')
                        ->join('factory ft', "ft.id=o.factory_id", 'left')
                        ->join('wx_group g', 'oot.group_id=g.id', 'left')
                        ->where([
                            ['o.client_ordernum', 'in', $param['client_ordernum_all']],
                            ['o.status', 'in', [0, 1]],//99作废
                            ['oot.status', '=', 300],
                            ['oot.after_price', '>', 0],
                        ])->update([
                            'oot.admin_id_send_2' => ADMIN_ID,
                            'oot.time_send_2' => time(),
                            'oot.update_time' => time(),
                            'oot.status' => 302,
                        ]);
                    if ($temp != count($param['client_ordernum_all'])) {
                        Db::rollback();
                        return $this->json(11, '失败');
                    }
                    //4,业务log->wx_order_outgo_action_log表记录
                    $temp = $this->orderOutgoService->action_log([
                        'type' => 'afterFinishing_outTail',
                        'param' => [
                            'order_ids' => $param['client_ordernum_all'],
                        ],
                    ]);
                    if ($temp == false) {
                        Db::rollback();
                        return $this->json(12, '失败');
                    }
                    //5,成本->暂无
                    //6,财务->委外对帐--数据记录
                    $temp = $this->orderOutgoService->order_status_0([
                        'type' => 'afterFinishing_outTail',
                        'param' => [
                            'order_ids' => $param['client_ordernum_all'],
                        ],
                    ]);
                    if ($temp == false) {
                        Db::rollback();
                        return $this->json(13, '失败');
                    }
                    //7,经验->暂无
                    Db::commit();
                    return $this->json(1, '');
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    return $this->json(100, '失败');
                }
                break;
        }
    }

    /**
     * 外发管理》节点进度》后整中  退货
     * @date 2021/11/26
     * @author zhuguosen 905502314@qq.com
     */
    public function returnGoods()
    {
        if ($this->request->isAjax() || $this->request->param('export/d', 0) || $this->request->param('ajaxflag/d', 0) == 1) {
            //1,参数处理
            $param = $this->request->param();
            if ($param['order_id_all'] == '') {
                return $this->json(10, '请输入参数');
            }
            $param['order_id_all'] = explode(',', $param['order_id_all']);
            $resParam = [];
            foreach ($param['order_id_all'] as $k => $v) {
                $resParam[$v]['order_id'] = $v;
                foreach ($param as $k2 => $v2) {
                    $k2 == "after_refund_type_{$v}" && $resParam[$v]['after_refund_type'] = intval($v2);
                    $k2 == "after_refund_num_{$v}" && $resParam[$v]['after_refund_num'] = intval($v2);
                    $k2 == "after_refund_reason_{$v}" && $resParam[$v]['after_refund_reason'] = trim($v2);
                }
            }
            Db::startTrans();
            try {
                //2,业务->修改表 wx_order_outgo
                foreach ($resParam as $k => $v) {
                    $temp = db('order_outgo oot')
                        ->where([
                            ['oot.order_id', '=', $v['order_id']],
                            ['oot.status', '=', 300],
                        ])->update([
                            'status' => 301,
                            'admin_id_send_1' => ADMIN_ID,
                            'time_send_1' => time(),
                            'update_time' => time(),
                            'after_refund_reason' => $v['after_refund_reason'],
                            'after_refund_type' => $v['after_refund_type'],
                            'after_refund_num' => $v['after_refund_num'],
                        ]);
                    if ($temp != 1) {
                        Db::rollback();
                        return $this->json(10, '设置失败');
                    }
                }
                //3,业务log->wx_order_outgo_action_log表修改
                $temp = $this->orderOutgoService->action_log([
                    'type' => 'afterFinishing_returnGoods',
                    'param' => $resParam,
                ]);
                if ($temp == false) {
                    Db::rollback();
                    return $this->json(14, '设置失败');
                }
                //5,成本->暂无
                //6,财务->暂无
                //7,经验->暂无
                Db::commit();
                return $this->json(1, '保存成功');
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return $this->json(13, '设置失败');
            }
        }

        $client_ordernum_all = $this->request->param('client_ordernum_all/s', '');
        $client_ordernum_all = explode(',', $client_ordernum_all);
        //10，查询 上次返工原因 与返工计时信息
        $list = db('order o')
            ->field('o.id,o.client_ordernum 
                ,oot.after_refund_reason,oot.after_refund_type,oot.after_refund_num
                ,oot.status,oot.batch_status
                ')
            ->join('order_outgo oot', "o.id=oot.order_id", 'left')
            ->join('factory ft', "ft.id=o.factory_id", 'left')
            ->join('wx_group g', 'oot.group_id=g.id', 'left')
            ->where([
                ['o.client_ordernum', 'in', $client_ordernum_all],
                ['o.status', '=', 1],//99作废
                ['oot.status', '=', 300],
            ])->select();
        $order_id_all = [];
        $can_flag = 1;
        foreach ($list as $k => $v) {
            $order_id_all[] = $v['id'];
            if ($v['status'] == 300 && $v['batch_status'] == 0) {
                $can_flag = 0;
                break;
            }
        }
        $assign = [
            'list' => $list,
            'order_id_all' => implode(',', $order_id_all),
            'client_ordernum_all' => implode(',', $client_ordernum_all),
            'can_flag' => $can_flag,
//            'return_reason' => config('mimo.return_reason'),
        ];
        return $this->assign($assign)->fetch();
    }

    /**
     * 外发管理》节点进度》已退货
     * @date 2021/11/26
     * @author zhuguosen 905502314@qq.com
     */
    public function finishReturn()
    {
        if ($this->request->isAjax() || $this->request->param('export/d', 0) || $this->request->param('ajaxflag/d', 0) == 1) {
            $page = $this->request->param('page/d', 1);
            $limit = $this->request->param('limit/d', 20);
            $nodeData = $this->nodeSetAndView('finishReturn');
            if ($nodeData['code'] > 0) {
                return json($nodeData);
            }
            list($where, $whereRaw0) = $this->_where_finishReturn();
            $order = "oot.update_time desc";
            $list = db('order o')
                ->field('ft.type as ft_type,ft.name as ft_name,o.id,o.client_ordernum ,o.shipment_time,o.quantity,o.sku,o.type
                ,s.pic,s.ori_pic
                ,sum(osize.shicai_count) sum_shicai_count 
                ,g.mobile,g.name as g_name
                ,oot.time_send_1,oot.after_refund_type,oot.after_refund_num,oot.after_refund_reason')
                ->join('order_outgo oot', "o.id=oot.order_id", 'left')
                ->join('factory ft', "ft.id=o.factory_id", 'left')
                ->join('sku s', "o.sku=s.sku", 'left')
                ->join('order_size osize ', 'osize.order_id=o.id', 'left')
                ->join('wx_group g', 'oot.group_id=g.id', 'left')
                ->where($where)
                ->whereRaw($whereRaw0)->page($page)->limit($limit)->orderRaw($order)
                ->group('o.id')->select();
            $count = db('order o')
                ->join('order_outgo oot', "o.id=oot.order_id", 'left')
                ->join('factory ft', "ft.id=o.factory_id", 'left')
                ->join('sku s', "o.sku=s.sku", 'left')
                ->join('order_size osize ', 'osize.order_id=o.id', 'left')
                ->join('wx_group g', 'oot.group_id=g.id', 'left')
                ->where($where)
                ->whereRaw($whereRaw0)
                ->group('o.id')->count();
            foreach ($list as $k => $v) {
                $list[$k]['type_txt'] = arrayGet(config('mimo.order_type'), $v['type'], '');
                $list[$k]['pic_res'] = trim($v['ori_pic']) == '' ? $v['pic'] : $v['ori_pic'];
                $list[$k]['status_txt'] = '已退货';
                $temp = $v['shipment_time'] - time();
                if ($temp < 2 * 24 * 3600 && $temp > 0) {
                    $list[$k]['status_txt'] = '预警';
                } else {
                    $list[$k]['status_txt'] = '已超期';
                }
                $list[$k]['shipment_time'] = intval($list[$k]['shipment_time']) <= 0 ? '' : date('m-d', $list[$k]['shipment_time']);//出货时间
                //耗时天数
                $list[$k]['consume_day'] = $this->_consume_day($v['time_send_1']);
                //退货信息处理
                $list[$k]['after_refund_type_txt'] = $list[$k]['after_refund_type'] == 0 ? '整单退' : '数量退';
            }
            $list_last = [];
            foreach ($list as $k => $v) {
                $list_last["_{$v['client_ordernum']}"] = $v;
            }
            //获取各状态统计数据
            $status_sum = $this->_status_sum_sewing($where, $whereRaw0);
            $result = [
                'code' => 0,
                'msg' => '',
                'data' => $list_last,
                'pageInfo' => [
                    'count' => $count,
                    'maxPage' => ceil($count / $limit),
                ],
                'txt' => [
                ],
                'status_sum' => $status_sum,
            ];
            return json($result);
        }
        $assign = [
            'factoryAll' => $this->_factorylist([
                'ft_type' => 1,
            ], true),
            'client_ordernum' => $this->request->param('client_ordernum/s', ''),
            'sku' => $this->request->param('sku/s', ''),
        ];
        return $this->assign($assign)->fetch();
    }

    private function _where_finishReturn()
    {
        $where = [
            ['ft.type', '=', 1],
        ];
        //订单加一级
        order_level($where, 'o.');
        $whereRaw0 = ' 1=1 ';
        $where[] = ["oot.status", "=", 301];
        $clientOrdernum = $this->request->param('client_ordernum/s', '');
        $sku = $this->request->param('sku/s', '');
        $factory_all = trim($this->request->param('factory_all'));
        $status_temp = intval($this->request->param('status_temp', 0));
        $createDateRange = $this->request->param('create_date_range/s', '');
        $shipment_date_range = $this->request->param('shipment_date_range/s', '');
        $time_send_1_range = $this->request->param('time_send_1_range/s', '');
        $consume_day = intval($this->request->param('consume_day/d', 0));
        if ($clientOrdernum == '') {
            $where[] = ['o.status', '<>', 99];
        }
        if ($clientOrdernum != '') {
            $where[] = ['o.client_ordernum', 'like', "%" . $clientOrdernum . "%"];
        }
        if ($sku != '') {
            $where[] = ['o.sku', 'like', "%" . $sku . "%"];
        }
        if ($factory_all != '') {
            $factory_all_array = explode(',', $factory_all);
            foreach ($factory_all_array as $k => $v) {
                $factory_all_array[$k] = intval($v);
            }
            $where[] = ['oot.group_id', 'in', $factory_all_array];
        }
        if ($createDateRange != '') {
            list($startTime, $endTime) = array_map('strtotime', explode('~', $createDateRange));
            $where[] = ['o.create_time', 'between', [$startTime, $endTime + 86399]];
        }
        if ($shipment_date_range != '') {
            list($startTime, $endTime) = array_map('strtotime', explode('~', $shipment_date_range));
            $where[] = ['o.shipment_time', 'between', [$startTime, $endTime + 86399]];
        }
        if ($time_send_1_range != '') {
            list($startTime, $endTime) = array_map('strtotime', explode('~', $time_send_1_range));
            $where[] = ['oot.time_send_1', 'between', [$startTime, $endTime + 86399]];
        }
        if ($consume_day > 0) {
            switch ($consume_day) {
                case 1:
                case 2:
                case 3:
                case 4:
                case 5:
                    $consume_day--;
                    $temp2 = $this->now - (($consume_day + 1) * 24 * 3600);
                    $temp = $this->now - ($consume_day * 24 * 3600);
                    $where[] = ['oot.time_send_1', '<=', $temp];
                    $where[] = ['oot.time_send_1', '>', $temp2];
                    break;
                case 104://4天以上
                    $temp = $this->now - (5 * 24 * 3600);
                    $where[] = ['oot.time_send_1', '<=', $temp];
                    break;
            }
        }
        switch ($status_temp) {//容易出现，注意下。 [Err] 1690 - BIGINT UNSIGNED value is out of range in '(`020mimo_com_local`.`o`.`shipment_time` - <cache>(unix_timestamp(now())))'
            case 1://车缝中  o.shipment_time - ( UNIX_TIMESTAMP(NOW()) )  < 0  容易出错 [Err] 1690 - BIGINT UNSIGNED
                $whereRaw0 = ' o.shipment_time >=  2 * 24 * 3600 + UNIX_TIMESTAMP(NOW()) ';
                break;
            case 2://预警
                $whereRaw0 = 'o.shipment_time   <  2 * 24 * 3600+UNIX_TIMESTAMP(NOW()) and o.shipment_time > UNIX_TIMESTAMP(NOW()) ';
                break;
            case 3://已超期
                $whereRaw0 = ' o.shipment_time  < UNIX_TIMESTAMP(NOW())';
                break;
        }
        return [$where, $whereRaw0];
    }

    /**
     * 外发管理》节点进度》外协尾部
     * @date 2021/11/26
     * @author zhuguosen 905502314@qq.com
     */
    public function outgoTail()
    {
        if ($this->request->isAjax() || $this->request->param('export/d', 0) || $this->request->param('ajaxflag/d', 0) == 1) {
            $page = $this->request->param('page/d', 1);
            $limit = $this->request->param('limit/d', 20);
            $nodeData = $this->nodeSetAndView('outgoTail');
            if ($nodeData['code'] > 0) {
                return json($nodeData);
            }
            list($where, $whereRaw0) = $this->_where_outgoTail();
            $order = "oot.update_time desc";
            $list = db('order o')
                ->field('ft.type as ft_type,ft.name as ft_name,o.id,o.client_ordernum ,o.shipment_time,o.quantity,o.sku,o.type
                ,s.pic,s.ori_pic
                ,sum(osize.shicai_count) sum_shicai_count 
                ,g.mobile,g.name as g_name
                ,oot.after_num,oot.outgotail_return_time,oot.time_send_2
                ')
                ->join('order_outgo oot', "o.id=oot.order_id", 'left')
                ->join('factory ft', "ft.id=o.factory_id", 'left')
                ->join('sku s', "o.sku=s.sku", 'left')
                ->join('order_size osize ', 'osize.order_id=o.id', 'left')
                ->join('wx_group g', 'oot.group_id=g.id', 'left')
                ->where($where)
                ->whereRaw($whereRaw0)->page($page)->limit($limit)->orderRaw($order)
                ->group('o.id')->select();
            $count = db('order o')
                ->join('order_outgo oot', "o.id=oot.order_id", 'left')
                ->join('factory ft', "ft.id=o.factory_id", 'left')
                ->join('sku s', "o.sku=s.sku", 'left')
                ->join('order_size osize ', 'osize.order_id=o.id', 'left')
                ->join('wx_group g', 'oot.group_id=g.id', 'left')
                ->where($where)
                ->whereRaw($whereRaw0)
                ->group('o.id')->count();
            foreach ($list as $k => $v) {
                $list[$k]['type_txt'] = arrayGet(config('mimo.order_type'), $v['type'], '');
                $list[$k]['pic_res'] = trim($v['ori_pic']) == '' ? $v['pic'] : $v['ori_pic'];
                $list[$k]['status_txt'] = '已退货';
                $temp = $v['shipment_time'] - time();
                if ($temp < 2 * 24 * 3600 && $temp > 0) {
                    $list[$k]['status_txt'] = '预警';
                } else {
                    $list[$k]['status_txt'] = '已超期';
                }
                $list[$k]['shipment_time'] = intval($list[$k]['shipment_time']) <= 0 ? '' : date('m-d', $list[$k]['shipment_time']);//出货时间
                //耗时天数
                $list[$k]['consume_day'] = $this->_consume_day($v['time_send_2']);
            }
            $list_last = [];
            foreach ($list as $k => $v) {
                $list_last["_{$v['client_ordernum']}"] = $v;
            }
            //获取各状态统计数据
            $status_sum = $this->_status_sum_sewing($where, $whereRaw0);
            $result = [
                'code' => 0,
                'msg' => '',
                'data' => $list_last,
                'pageInfo' => [
                    'count' => $count,
                    'maxPage' => ceil($count / $limit),
                ],
                'txt' => [
                ],
                'status_sum' => $status_sum,
            ];
            return json($result);
        }
        $assign = [
            'factoryAll' => $this->_factorylist([
                'ft_type' => 1,
            ], true),
            'client_ordernum' => $this->request->param('client_ordernum/s', ''),
            'sku' => $this->request->param('sku/s', ''),
        ];
        return $this->assign($assign)->fetch();
    }

    private function _where_outgoTail()
    {
        $where = [
            ['ft.type', '=', 1],
        ];
        //订单加一级
        order_level($where, 'o.');
        $whereRaw0 = ' 1=1 ';
        $where[] = ["oot.status", "=", 302];
        $clientOrdernum = $this->request->param('client_ordernum/s', '');
        $sku = $this->request->param('sku/s', '');
        $factory_all = trim($this->request->param('factory_all'));
        $status_temp = intval($this->request->param('status_temp', 0));
        $consume_day = intval($this->request->param('consume_day/d', 0));
        $createDateRange = $this->request->param('create_date_range/s', '');
        $shipment_date_range = $this->request->param('shipment_date_range/s', '');
        $outgotail_return_date_range = $this->request->param('outgotail_return_date_range/s', '');
        $time_send_2_range = $this->request->param('time_send_2_range/s', '');
        if ($clientOrdernum == '') {
            $where[] = ['o.status', '<>', 99];
        }
        if ($clientOrdernum != '') {
            $where[] = ['o.client_ordernum', 'like', "%" . $clientOrdernum . "%"];
        }
        if ($sku != '') {
            $where[] = ['o.sku', 'like', "%" . $sku . "%"];
        }
        if ($factory_all != '') {
            $factory_all_array = explode(',', $factory_all);
            foreach ($factory_all_array as $k => $v) {
                $factory_all_array[$k] = intval($v);
            }
            $where[] = ['oot.group_id', 'in', $factory_all_array];
        }
        if ($createDateRange != '') {
            list($startTime, $endTime) = array_map('strtotime', explode('~', $createDateRange));
            $where[] = ['o.create_time', 'between', [$startTime, $endTime + 86399]];
        }
        if ($shipment_date_range != '') {
            list($startTime, $endTime) = array_map('strtotime', explode('~', $shipment_date_range));
            $where[] = ['o.shipment_time', 'between', [$startTime, $endTime + 86399]];
        }
        if ($time_send_2_range != '') {
            list($startTime, $endTime) = array_map('strtotime', explode('~', $time_send_2_range));
            $where[] = ['oot.time_send_2', 'between', [$startTime, $endTime + 86399]];
        }
        if ($consume_day > 0) {
            switch ($consume_day) {
                case 1:
                case 2:
                case 3:
                case 4:
                case 5:
                    $consume_day--;
                    $temp2 = $this->now - (($consume_day + 1) * 24 * 3600);
                    $temp = $this->now - ($consume_day * 24 * 3600);
                    $where[] = ['oot.time_send_2', '<=', $temp];
                    $where[] = ['oot.time_send_2', '>', $temp2];
                    break;
                case 104://4天以上
                    $temp = $this->now - (5 * 24 * 3600);
                    $where[] = ['oot.time_send_2', '<=', $temp];
                    break;
            }
        }
        switch ($status_temp) {//容易出现，注意下。 [Err] 1690 - BIGINT UNSIGNED value is out of range in '(`020mimo_com_local`.`o`.`shipment_time` - <cache>(unix_timestamp(now())))'
            case 1://车缝中  o.shipment_time - ( UNIX_TIMESTAMP(NOW()) )  < 0  容易出错 [Err] 1690 - BIGINT UNSIGNED
                $whereRaw0 = ' o.shipment_time >=  2 * 24 * 3600 + UNIX_TIMESTAMP(NOW()) ';
                break;
            case 2://预警
                $whereRaw0 = 'o.shipment_time   <  2 * 24 * 3600+UNIX_TIMESTAMP(NOW()) and o.shipment_time > UNIX_TIMESTAMP(NOW()) ';
                break;
            case 3://已超期
                $whereRaw0 = ' o.shipment_time  < UNIX_TIMESTAMP(NOW())';
                break;
        }
        if ($outgotail_return_date_range != '') {
            list($startTime, $endTime) = array_map('strtotime', explode('~', $outgotail_return_date_range));
            $where[] = ['oot.outgotail_return_time', 'between', [$startTime, $endTime + 86399]];
        }
        return [$where, $whereRaw0];
    }

    /**
     * 外发管理》节点进度》已完成--按了尾部完成后 的查询
     * @date 2021/11/26
     * @author zhuguosen 905502314@qq.com
     */
    public function allFinish()
    {
        if ($this->request->isAjax() || $this->request->param('export/d', 0) || $this->request->param('ajaxflag/d', 0) == 1) {
            $page = $this->request->param('page/d', 1);
            $limit = $this->request->param('limit/d', 20);
            $nodeData = $this->nodeSetAndView('allFinish');
            if ($nodeData['code'] > 0) {
                return json($nodeData);
            }
            $where = $this->_where_allFinish();

            $order = "oot.update_time desc";
            $list = db('order o')
                ->field('ft.type as ft_type,ft.name as ft_name,o.id,o.client_ordernum ,o.shipment_time,o.quantity,o.sku,o.type
                ,o.tail_status,o.delivery_sync_status
                ,s.pic,s.ori_pic
                ,sum(osize.shicai_count) sum_shicai_count 
                ,g.mobile,g.name as g_name
                ,oot.time_send_1,oot.after_refund_type,oot.after_refund_num,oot.after_refund_reason')
                ->join('order_outgo oot', "o.id=oot.order_id", 'left')
                ->join('factory ft', "ft.id=o.factory_id", 'left')
                ->join('sku s', "o.sku=s.sku", 'left')
                ->join('order_size osize ', 'osize.order_id=o.id', 'left')
                ->join('wx_group g', 'oot.group_id=g.id', 'left')
                ->where($where)
                ->page($page)->limit($limit)->orderRaw($order)
                ->group('o.id')->select();
            $count = db('order o')
                ->join('order_outgo oot', "o.id=oot.order_id", 'left')
                ->join('factory ft', "ft.id=o.factory_id", 'left')
                ->join('sku s', "o.sku=s.sku", 'left')
                ->join('order_size osize ', 'osize.order_id=o.id', 'left')
                ->join('wx_group g', 'oot.group_id=g.id', 'left')
                ->where($where)
                ->group('o.id')->count();
            $orderSizeService = new OrderSizeService();
            // 获取有发货单的订单
            $orderDeliveryList = db('order_delivery')->where('order_id', 'in', array_column($list, 'id'))->group('order_id')->column('order_id');
            foreach ($list as $k => $v) {
                $list[$k]['type_txt'] = arrayGet(config('mimo.order_type'), $v['type'], '');
                $list[$k]['pic_res'] = trim($v['ori_pic']) == '' ? $v['pic'] : $v['ori_pic'];
                $list[$k]['status_txt'] = '已完成';
                $list[$k]['shipment_time'] = intval($list[$k]['shipment_time']) <= 0 ? '' : date('m-d', $list[$k]['shipment_time']);//出货时间
                //退货信息处理
                $list[$k]['after_refund_type_txt'] = $list[$k]['after_refund_type'] == 0 ? '整单退' : '数量退';
                //其它操作》库存录入要的格式细码数据
                $osList = $orderSizeService->getListByOrderId($v['id'], 'mid,order_count,daohuo_count,shicai_count,jiaohuo_tail_count,delivery_count,jiaohuo_count,size_name,tail_stock_in_out,tail_defective');
                $list[$k]['osJson'] = json_encode($osList);
                $otherStockList = db('sku_stock')->where(['sku' => $v['sku']])->where('client_ordernum', 'not in', [$v['client_ordernum']])
                    ->field('dress_line_code,size_name,sum(available_count) as available_count,sum(defective_count) as defective_count')->group("size_name")->select();
                $list[$k]['otherStockList_json'] = json_encode($otherStockList);
                $list[$k]['finishinfo'] = db('order_finish')->where(['order_id' => $v['id']])->find();
                $list[$k]['is_delivery'] = in_array($v['id'], $orderDeliveryList) ? 1 : 0; // 是否有发货单
            }
            $list_last = [];
            foreach ($list as $k => $v) {
                $list_last["_{$v['client_ordernum']}"] = $v;
            }
            //获取各状态统计数据
            $status_sum = $this->_status_sum_allFinish($where);
            $result = [
                'code' => 0,
                'msg' => '',
                'data' => $list_last,
                'pageInfo' => [
                    'count' => $count,
                    'maxPage' => ceil($count / $limit),
                ],
                'txt' => [
                ],
                'status_sum' => $status_sum,
            ];
            return json($result);
        }
        $assign = [
            'factoryAll' => $this->_factorylist([
                'ft_type' => 1,
            ], true),
            'client_ordernum' => $this->request->param('client_ordernum/s', ''),
            'sku' => $this->request->param('sku/s', ''),
        ];
        return $this->assign($assign)->fetch();
    }

    private function _where_allFinish()
    {
        $where = [
            ['ft.type', '=', 1],
        ];
        //订单加一级
        order_level($where, 'o.');
        $where[] = ["oot.status", "=", 1000];
        $clientOrdernum = $this->request->param('client_ordernum/s', '');
        $sku = $this->request->param('sku/s', '');
        $shipment_date_range = $this->request->param('shipment_date_range/s', '');
        $tail_over_time_range = $this->request->param('tail_over_time_range/s', '');
        $factory_parent = intval($this->request->param('factory_parent', 0));
        $factory_child = intval($this->request->param('factory_child', 0));
        $factory_all = trim($this->request->param('factory_all'));
        if ($clientOrdernum == '') {
            $where[] = ['o.status', '<>', 99];
        }
        if ($clientOrdernum != '') {
            $where[] = ['o.client_ordernum', 'like', "%" . $clientOrdernum . "%"];
        }
        if ($sku != '') {
            $where[] = ['o.sku', 'like', "%" . $sku . "%"];
        }
        if ($shipment_date_range != '') {
            list($startTime, $endTime) = array_map('strtotime', explode('~', $shipment_date_range));
            $where[] = ['o.shipment_time', 'between', [$startTime, $endTime + 86399]];
        }
        if ($tail_over_time_range != '') {
            list($startTime, $endTime) = array_map('strtotime', explode('~', $tail_over_time_range));
            $where[] = ['o.tail_over_time', 'between', [$startTime, $endTime + 86399]];
        }
        if ($factory_parent > 0) {
            $where[] = ['o.factory_id', '=', $factory_parent];
        }
        if ($factory_child > 0) {
            $where[] = ['oot.group_id', '=', $factory_child];
        }
        if ($factory_all != '') {
            $factory_all_array = explode(',', $factory_all);
            foreach ($factory_all_array as $k => $v) {
                $factory_all_array[$k] = intval($v);
            }
            $where[] = ['oot.group_id', 'in', $factory_all_array];
        }
        return $where;
    }

    private function _status_sum_allFinish($where)
    {
        $info_0 = db('order o')
            ->field('count(o.id) as count,sum(o.quantity) as sum_quantity
                ')
            ->join('order_outgo oot', "o.id=oot.order_id", 'left')
            ->join('factory ft', "ft.id=o.factory_id", 'left')
            ->join('sku s', "o.sku=s.sku", 'left')
            ->join('wx_group g', 'oot.group_id=g.id', 'left')
            ->where($where)
            ->find();
        $res = [];
        $res[] = [
            'name' => '已完成',
            'count' => $info_0['count'],
            'sum_quantity' => floatval($info_0['sum_quantity']),
        ];
        return $res;
    }

    /**
     * 订单进度与码数信息
     * @author zhuguosen 905502314@qq.com
     * @date 2022/5/8
     */
    public function getOrderDetail()
    {
        $orderId = $this->request->param('order_id/id', 0);
        //1,查询信息
        $where = [];
        $where[] = ['o.id', '=', $orderId];
        $info = db('order o')
            ->field("o.id,o.client_ordernum,o.status
                ,group_concat(distinct os.mid,',', os.size_name,',',os.order_count ,',',os.shicai_count,',',os.jiaohuo_count,',',os.jiaohuo_tail_count,',',os.delivery_count,',',os.daohuo_count,',',os.store_count  SEPARATOR ';') as order_size_list
                ,o.shipment_time,o.over_time,o.create_time,o.caigou_over_time,o.caichuang_over_time
                ,o.chejian_over_time,o.tail_over_time,o.delivery_time,o.store_time
                ,o.real_shipment_status,o.real_shipment_time
                ,min(od.delivery_time) as od_delivery_time
                ,o.caigou_user_id,u.username as caigou_user_name
                ,o.caichuang_user_id,u2.username as caichuang_user_name
                ,oot.status as status_oot ,oot.batch_status,oot.batch_num,oot.sew_return_goods_num
                ,oot.time_send_0,oot.time_return_0
                ,u3.username as admin_id_send_0_user_name,u4.username as admin_id_return_0_username
                ")
            ->join('order_outgo oot', "o.id=oot.order_id", 'left')
            ->join('order_size os ', 'os.order_id=o.id', 'left')
            ->join('system_user u ', 'o.caigou_user_id=u.id', 'left')
            ->join('system_user u2 ', 'o.caichuang_user_id=u2.id', 'left')
            ->join('system_user u3 ', 'oot.admin_id_send_0=u3.id', 'left')
            ->join('system_user u4 ', 'oot.admin_id_return_0=u4.id', 'left')
            ->join('order_delivery od ', 'o.id=od.order_id and od.delivery_status not in (6,7)', 'left')
            ->where($where)
            ->group('o.id')->find();
        $info['osList'] = $osList = $this->_deal_order_size_list($info['order_size_list']);
        //3,每个环节的数据整理
        $info['jieList'] = [
            'xia_dan' => [
                'jie' => '下单',
                'size' => [],
                'sum' => 0,
                'time' => date('Y-m-d H:i:s', $info['create_time']),
                'user_name' => '系统自动',
            ],
            'caigou' => [
                'jie' => '采购',
                'size' => [],
                'sum' => 0,
                'time' => date('Y-m-d H:i:s', $info['caigou_over_time']),
                'user_name' => $info['caigou_user_name'],
            ],
            'caichuang' => [
                'jie' => '裁床',
                'size' => [],
                'sum' => 0,
                'time' => date('Y-m-d H:i:s', $info['caichuang_over_time']),
                'user_name' => $info['caichuang_user_name'],
            ],
            'caipian_fahuo' => [
                'jie' => '裁片发货',
                'size' => [],
                'sum' => 0,
                'time' => date('Y-m-d H:i:s', $info['time_send_0']),
                'user_name' => $info['admin_id_send_0_user_name'],
            ],
        ];
        //分批回货信息设置
        $this->_getOrderDetail_batch_list($info);
        $chejian = [
            'chejian' => [
                'jie' => '车间',
                'size' => [],
                'sum' => 0,
                'time' => date('Y-m-d H:i:s', $info['chejian_over_time']),
                'user_name' => '',
            ],
        ];
        $return_info = $this->_getOrderDetail_return_info($info);
        $out_tail = $this->_getOrderDetail_out_tail($info);
        $jieList = [
            'tail' => [
                'jie' => '后整',
                'size' => [],
                'sum' => 0,
                'time' => date('Y-m-d H:i:s', $info['tail_over_time']),
                'user_name' => '',
            ],
            'delivery' => [
                'jie' => '发货(MES)',
                'size' => [],
                'sum' => 0,
                'time' => date('Y-m-d H:i:s', $info['real_shipment_time']),
                'user_name' => '',
            ],
            'store' => [
                'jie' => '入仓',
                'size' => [],
                'sum' => 0,
                'time' => date('Y-m-d H:i:s', $info['store_time']),
                'user_name' => '',
            ],
        ];
        $info['jieList'] = array_merge($info['jieList'], $chejian, $return_info, $out_tail, $jieList);
        foreach ($info['osList'] as $k => $v) {
            $info['jieList']['xia_dan']['size'][] = [
                'size_name' => $v['size_name'],
                'num' => $v['order_count'],
            ];
            $info['jieList']['xia_dan']['sum'] += $v['order_count'];
            $info['jieList']['caigou']['size'][] = [
                'size_name' => $v['size_name'],
                'num' => $v['order_count'],
            ];
            $info['jieList']['caigou']['sum'] += $v['order_count'];
            $info['jieList']['caichuang']['size'][] = [
                'size_name' => $v['size_name'],
                'num' => $v['shicai_count'],
            ];
            $info['jieList']['caichuang']['sum'] += $v['shicai_count'];
            $info['jieList']['chejian']['size'][] = [
                'size_name' => $v['size_name'],
                'num' => $v['jiaohuo_count'],
            ];
            $info['jieList']['chejian']['sum'] += $v['jiaohuo_count'];
            $info['jieList']['tail']['size'][] = [
                'size_name' => $v['size_name'],
                'num' => $v['jiaohuo_tail_count'],
            ];
            $info['jieList']['tail']['sum'] += $v['jiaohuo_tail_count'];
            $info['jieList']['delivery']['size'][] = [
                'size_name' => $v['size_name'],
                'num' => $v['delivery_count'],
            ];
            $info['jieList']['delivery']['sum'] += $v['delivery_count'];
            $info['jieList']['store']['size'][] = [
                'size_name' => $v['size_name'],
                'num' => $v['store_count'],
            ];
            $info['jieList']['store']['sum'] += $v['store_count'];
        }
        //清理没有的节点
        if ($info['caigou_over_time'] <= 0) {
            unset($info['jieList']['caigou']);
        }
        if ($info['caichuang_over_time'] <= 0) {
            unset($info['jieList']['caichuang']);
        }
        if ($info['chejian_over_time'] <= 0) {
            unset($info['jieList']['chejian']);
        }
        if ($info['tail_over_time'] <= 0) {
            unset($info['jieList']['tail']);
        }
        if (intval($info['real_shipment_time']) <= 0) {
            unset($info['jieList']['delivery']);
        }
        if ($info['store_time'] <= 0) {
            unset($info['jieList']['store']);
        }
        //插入委外进度的数据--裁片发货
        if (isset($info['jieList']['caichuang']) && $info['status_oot'] >= 200) {
            foreach ($info['osList'] as $k => $v) {
                $info['jieList']['caipian_fahuo']['size'][] = [
                    'size_name' => $v['size_name'],
                    'num' => 0,
                ];
                $info['jieList']['caipian_fahuo']['sum'] = $info['jieList']['caichuang']['sum'];
            }
        } else {
            unset($info['jieList']['caipian_fahuo']);
        }
        $this->assign('info', $info);
        return json(['code' => 0, 'msg' => '', 'data' => $this->fetch()->getContent()]);
    }

    private function _getOrderDetail_batch_list(&$info)
    {
        if ($info['status_oot'] < 300) {
            return true;
        }
        //旧数据处理 与，只有1个批次的回货
        if ($info['batch_status'] == 1 && $info['batch_num'] <= 1) {
            return true;
        }
        $batch_list = db('order_outgo_batch bh')
            ->field("bh.num,bh.size_mid,bh.size_name,bh.count,bh.admin_id,bh.create_time,u.username")
            ->join('system_user u ', 'bh.admin_id=u.id', 'left')
            ->where([
                ['bh.order_id', '=', $info['id']],
                ['bh.type', '=', 'return'],
            ])
            ->group('bh.num,bh.size_name')
            ->order('bh.num asc')
            ->select();
        for ($i = 1; $i <= $info['batch_num']; $i++) {
            $info['jieList']["batch_{$i}"] = [
                'jie' => "分批回货{$i}",
                'size' => [],
                'sum' => 0,
                'time' => '',//date('Y-m-d H:i:s', $info['time_return_0']) $info['admin_id_return_0_username']
                'user_name' => '',
            ];
            foreach ($info['osList'] as $k => $v) {
                $size_name_num = 0;
                $time = '';
                $user_name = '';
                foreach ($batch_list as $k2 => $v2) {
                    if ($i == $v2['num'] && $v2['size_name'] == $v['size_name']) {
                        $size_name_num += $v2['count'];
                        $time = date('Y-m-d H:i:s', $v2['create_time']);
                        $user_name = $v2['username'];
                    }
                }
                $info['jieList']["batch_{$i}"]['size'][] = [
                    'size_name' => $v['size_name'],
                    'num' => $size_name_num,
                ];
                $info['jieList']["batch_{$i}"]['sum'] += $size_name_num;
                $info['jieList']["batch_{$i}"]['time'] = $time;
                $info['jieList']["batch_{$i}"]['user_name'] = $user_name;
            }
        }
    }

    private function _getOrderDetail_return_info($info)
    {
        $log_info = db('order_outgo_action_log lg')
            ->field("lg.id,lg.return_goods_num,lg.create_time,u.username")
            ->join('system_user u ', 'lg.admin_id=u.id', 'left')
            ->where([
                ['lg.order_id', '=', $info['id']],
                ['lg.type', '=', 'finishReturn_confirmReturnGoods'],
            ])->order('lg.id desc')->find();
        if (!isset($log_info['id'])) {
            return [];
        }
        $info['jieList']["return_info"] = [
            'jie' => '退货',
            'size' => [],
            'sum' => 0,
            'time' => date('Y-m-d H:i:s', $log_info['create_time']),
            'user_name' => $log_info['username'],
        ];
        foreach ($info['osList'] as $k => $v) {
            $info['jieList']["return_info"]['size'][] = [
                'size_name' => $v['size_name'],
                'num' => 0,
            ];
            $info['jieList']["return_info"]['sum'] = $log_info['return_goods_num'];
        }
        return [
            "return_info" => $info['jieList']["return_info"],
        ];
    }

    private function _getOrderDetail_out_tail($info)
    {
        $log_info = db('order_outgo_action_log lg')
            ->field("lg.id,lg.return_goods_num,lg.create_time,u.username")
            ->join('system_user u ', 'lg.admin_id=u.id', 'left')
            ->where([
                ['lg.order_id', '=', $info['id']],
                ['lg.type', '=', 'outgoTail_confirmReturnGoods'],
            ])->order('lg.id desc')->find();
        if (!isset($log_info['id'])) {
            return [];
        }
        $info['jieList']["out_tail"] = [
            'jie' => '外协尾部',
            'size' => [],
            'sum' => 0,
            'time' => date('Y-m-d H:i:s', $log_info['create_time']),
            'user_name' => $log_info['username'],
        ];
        foreach ($info['osList'] as $k => $v) {
            $info['jieList']["out_tail"]['size'][] = [
                'size_name' => $v['size_name'],
                'num' => 0,
            ];
            $info['jieList']["out_tail"]['sum'] = $log_info['return_goods_num'];
        }
        return [
            "out_tail" => $info['jieList']["out_tail"],
        ];
    }

    //尺码细数
    public function getQuantityDetail()
    {
        $orderId = $this->request->param('order_id/id', 0);
        $type = $this->request->param('type/s', 'order_count');
        switch ($type) {
            case 'shicai_count':
                $orderSizeService = new OrderSizeService();
                $osList = $orderSizeService->getListByOrderId($orderId, "size_name,shicai_count");
                $osList[] = ['size_name' => '合计', 'shicai_count' => array_sum(array_column($osList, 'shicai_count'))];
                $data['data'] = $osList;
                return $data;
                break;
            default:
                $orderSizeService = new OrderSizeService();
                $osList = $orderSizeService->getListByOrderId($orderId, 'size_name,order_count');
                $osList[] = ['size_name' => '合计', 'order_count' => array_sum(array_column($osList, 'order_count'))];
                $data['data'] = $osList;
                return $data;
                break;
        }
    }

    /**
     * 搜索订单号，sku时确定节点显示,并带上 参数。
     * @param $where
     * @author zhuguosen 905502314@qq.com
     * @date 2022/3/17
     */
    public function nodeSetAndView($view)
    {
        //1,是否查询订单号，sku。如不是就不用判断了。
        $clientOrdernum = $this->request->param('client_ordernum/s', '');
        $sku = $this->request->param('sku/s', '');
        if ($clientOrdernum == '' && $sku == '') {
            return ['code' => 0];
        }
        //2,首先查询是否在原页面查询
        $count = $this->_nodeSetAndView_min($view);
        if ($count > 0) {
            return ['code' => 0];
        }
        //3,按顺充节点查询订单，如都没有就不动，如有就跳转页面
        $views = [
            'index' => [],
            'cutting' => [],
            'waitDeliver' => [],
            'sewing' => [],
            'afterFinishing' => [],
            'finishReturn' => [],
            'outgoTail' => [],
            'allFinish' => [],
        ];
        foreach ($views as $k => $v) {
            $count = $this->_nodeSetAndView_min($k, $v);
            if ($count > 0 && $k != $view) {
                return [
                    'code' => 10001,
                    'url' => url($k, [
                            'client_ordernum' => $clientOrdernum,
                            'sku' => $sku,
                        ]
                    )
                ];
            }
        }
        return ['code' => 0];
    }

    public function _nodeSetAndView_min($view, $ext = [])
    {
        switch ($view) {
            case 'dispatching':
                $where = $this->_where_dispatching();
                $count = db('order o')
                    ->join('order_outgo oot', "o.id=oot.order_id", 'left')
                    ->join('factory ft', "ft.id=o.factory_id", 'left')
                    ->join('group g', "oot.group_id=g.id", 'left')
                    ->join('sku s', "o.sku=s.sku", 'left')
                    ->join('distributing ds', "o.id=ds.order_id", 'left')
                    ->join('order_size osize ', 'osize.order_id=o.id', 'left')
                    ->where($where)
                    ->group('o.id')->count();
                if ($count > 0) {
                    return $count;
                }
                break;
            case 'index':
                $where = $this->_where_index();
                $count = db('order o')
                    ->field('ft.type as ft_type,ft.name as ft_name,o.id,o.client_ordernum ,o.shipment_time,o.quantity
                ,s.pic')
                    ->join('factory ft', "ft.id=o.factory_id", 'left')
                    ->join('order_outgo oot', "oot.order_id=o.id", 'left')
                    ->join('sku s', "o.sku=s.sku", 'left')
                    ->join('order_material om ', 'om.order_id=o.id', 'left')
                    ->join('material ml ', 'om.material_id=ml.id', 'left')
                    ->where($where)->group('o.id')->count();
                if ($count > 0) {
                    return $count;
                }
                break;
            case 'cutting':
                $where = $this->_where_cutting();
                $count = db('order o')
                    ->field('o.id')
                    ->join('factory ft', "ft.id=o.factory_id", 'left')
                    ->join('sku s', "o.sku=s.sku", 'left')
                    ->join('order_outgo oot', "o.id=oot.order_id", 'left')
                    ->join('wx_order_material om ', 'om.order_id=o.id', 'left')
                    ->join('wx_material ml ', 'om.material_id=ml.id', 'left')
                    ->where($where)->group('om.order_id')->count('o.id');
                if ($count > 0) {
                    return $count;
                }
                break;
            case 'waitDeliver':
                $where = $this->_where_waitDeliver();
                $count = db('order o')
                    ->join('order_outgo oot', "o.id=oot.order_id", 'left')
                    ->join('factory ft', "ft.id=o.factory_id", 'left')
                    ->join('sku s', "o.sku=s.sku", 'left')
                    ->join('distributing ds', "o.id=ds.order_id", 'left')
                    ->join('order_size osize ', 'osize.order_id=o.id', 'left')
                    ->where($where)
                    ->group('o.id')->count();
                if ($count > 0) {
                    return $count;
                }
                break;
            case 'sewing':
                list($where, $whereRaw0) = $this->_where_sewing();
                $count = db('order o')
                    ->join('order_outgo oot', "o.id=oot.order_id", 'left')
                    ->join('factory ft', "ft.id=o.factory_id", 'left')
                    ->join('sku s', "o.sku=s.sku", 'left')
                    ->join('order_size osize ', 'osize.order_id=o.id', 'left')
                    ->join('wx_group g', 'oot.group_id=g.id', 'left')
                    ->where($where)
                    ->whereRaw($whereRaw0)
                    ->group('o.id')->count();
                if ($count > 0) {
                    return $count;
                }
                break;
            case 'afterFinishing':
                list($where, $whereRaw0) = $this->_where_afterFinishing();
                $count = db('order o')
                    ->join('order_outgo oot', "o.id=oot.order_id", 'left')
                    ->join('factory ft', "ft.id=o.factory_id", 'left')
                    ->join('sku s', "o.sku=s.sku", 'left')
                    ->join('order_size osize ', 'osize.order_id=o.id', 'left')
                    ->join('wx_group g', 'oot.group_id=g.id', 'left')
                    ->where($where)
                    ->whereRaw($whereRaw0)
                    ->group('o.id')->count();
                if ($count > 0) {
                    return $count;
                }
                break;
            case 'finishReturn':
                list($where, $whereRaw0) = $this->_where_finishReturn();
                $count = db('order o')
                    ->join('order_outgo oot', "o.id=oot.order_id", 'left')
                    ->join('factory ft', "ft.id=o.factory_id", 'left')
                    ->join('sku s', "o.sku=s.sku", 'left')
                    ->join('order_size osize ', 'osize.order_id=o.id', 'left')
                    ->join('wx_group g', 'oot.group_id=g.id', 'left')
                    ->where($where)
                    ->whereRaw($whereRaw0)
                    ->group('o.id')->count();
                if ($count > 0) {
                    return $count;
                }
                break;
            case 'outgoTail':
                list($where, $whereRaw0) = $this->_where_outgoTail();
                $count = db('order o')
                    ->join('order_outgo oot', "o.id=oot.order_id", 'left')
                    ->join('factory ft', "ft.id=o.factory_id", 'left')
                    ->join('sku s', "o.sku=s.sku", 'left')
                    ->join('order_size osize ', 'osize.order_id=o.id', 'left')
                    ->join('wx_group g', 'oot.group_id=g.id', 'left')
                    ->where($where)
                    ->whereRaw($whereRaw0)
                    ->group('o.id')->count();
                if ($count > 0) {
                    return $count;
                }
                break;
            case 'allFinish':
                $where = $this->_where_allFinish();
                $count = db('order o')
                    ->join('order_outgo oot', "o.id=oot.order_id", 'left')
                    ->join('factory ft', "ft.id=o.factory_id", 'left')
                    ->join('sku s', "o.sku=s.sku", 'left')
                    ->join('order_size osize ', 'osize.order_id=o.id', 'left')
                    ->join('wx_group g', 'oot.group_id=g.id', 'left')
                    ->where($where)
                    ->group('o.id')->count();
                if ($count > 0) {
                    return $count;
                }
                break;
        }
        return 0;
    }

    /**
     * 工厂的委外倍率设置
     * @author zhuguosen 905502314@qq.com
     * @date 2022/3/24
     */
    public function unitSet()
    {
        if ($this->request->isAjax() || $this->request->param('export/d', 0) || $this->request->param('ajaxflag/d', 0) == 1) {
            //检查用户有没这权限修改 wx_system_menu表的title=委外设置全部修改权的id值
            $system_menu_info = db('system_menu')->where('url="mp/OutNodeProgress/unitSet" and param="can_edit=1"')->find();
            $can_edit = isset($system_menu_info['id']) ? RoleModel::checkAuth($system_menu_info['id']) : false;
            //1,参数处理
            $param = [
                'order_id' => $this->request->param('order_id/d', 0),
                'u_out_type' => $this->request->param('u_out_type/s', ''),
                'u_scale' => floatval($this->request->param('u_scale', 0)),
                'u_price_manual' => floatval($this->request->param('u_price_manual', 0)),
                'u_scale_changkuan' => floatval($this->request->param('u_scale_changkuan', 0)),

                'cost_jiagong_littleSumCost' => floatval($this->request->param('cost_jiagong_littleSumCost', 0)),
                'cost_jiagong_scale' => floatval($this->request->param('cost_jiagong_scale', 0)),
                'cost_jiagong_sumCostForSale' => floatval($this->request->param('cost_jiagong_sumCostForSale', 0)),
            ];
            if ($param['u_out_type'] == '') {
                return $this->json(10, '请选择委外类型');
            }
            //$param['u_out_type'] 升序处理
            $temp0 = explode(',', $param['u_out_type']);
            $temp1 = [];
            foreach ($temp0 as $k => $v) {
                intval($v) > 0 && $temp1[] = intval($v);
            }
            sort($temp1);
            $param['u_out_type'] = implode(',', $temp1);
            if ($param['u_scale'] <= 0 && $param['u_price_manual'] <= 0) {
                return $this->json(11, '请设置委外倍率（车缝价）或 手工/专机单价');
            }
            $info = db('order_outgo oot')
                ->where([
                    ['oot.order_id', '=', $param['order_id']],
                ])->find();
            if (($can_edit == false && !isset($info['group_id']))
                || ($can_edit == false && $info['status'] >= 200)
            ) {
                return $this->json(10, '不可修改');
            }
            if ($can_edit == true && $info['status'] >= 200) {//特别权限，如黑客性修改
                Db::startTrans();
                try {
                    $res = $this->orderOutgoService->unitSet_super($param);
                    if ($res['code'] > 0) {
                        Db::rollback();
                        return $this->json($res['code'], $res['msg'], $res);
                    }
                    Db::commit();
                    return $this->json($res['code'], $res['msg']);
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    return $this->json(13, '设置失败', [$e->getMessage(), $e->getLine(), $e->getFile()]);
                }
            }
            if ($info['group_id'] == 0) {
                return $this->json(10, '请先设置子工厂或分组');
            }
            Db::startTrans();
            try {
                switch (env('env_site')) {
                    case 'riwei':
                        $temp = db('order_ext')->field('id')->where(['order_id' => $param['order_id']])->find();
                        if (isset($temp['id'])) {
                            db('order_ext')->where(['order_id' => $param['order_id']])->update([
                                'cost_jiagong_littleSumCost' => $param['cost_jiagong_littleSumCost'],
                                'cost_jiagong_scale' => $param['cost_jiagong_scale'],
                                'cost_jiagong_sumCostForSale' => $param['cost_jiagong_sumCostForSale'],
                            ]);
                        } else {
                            db('order_ext')->insert([
                                'order_id' => $param['order_id'],
                                'cost_jiagong_littleSumCost' => $param['cost_jiagong_littleSumCost'],
                                'cost_jiagong_scale' => $param['cost_jiagong_scale'],
                                'cost_jiagong_sumCostForSale' => $param['cost_jiagong_sumCostForSale'],
                                'create_time' => time(),
                                'update_time' => time(),
                            ]);
                        }

                        break;
                }
                //2,业务->修改表 wx_order_outgo
                $temp = db('order_outgo oot')
                    ->where([
                        ['oot.order_id', '=', $param['order_id']],
                    ])->update([
                        'update_time' => time(),
                        'admin_id' => ADMIN_ID,
//                        'status' => 100,
                        'u_out_type' => $param['u_out_type'],
                        'u_scale' => $param['u_scale'],
                        'u_price_manual' => $param['u_price_manual'],
                        'u_scale_changkuan' => $param['u_scale_changkuan'],
                    ]);
                if ($temp != 1) {
                    Db::rollback();
                    return $this->json(12, '设置失败');
                }
                //3,业务log->wx_order_outgo_action_log表修改
                $temp = $this->orderOutgoService->action_log([
                    'type' => 'dispatching_unitSet',
                    'param' => $param,
                ]);
                if ($temp == false) {
                    Db::rollback();
                    return $this->json(14, '设置失败');
                }
                //5,成本->暂无
                //6,财务->暂无
                //7,经验->暂无
                Db::commit();
                return $this->json(1, '保存成功');
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return $this->json(13, '设置失败', [$e->getCode(), $e->getMessage(), $e->getFile(), $e->getLine(), $e->getTrace()]);
            }
        }
        //1,显示参数处理
        $order_id = $this->request->param('order_id/d', 0);
        $type = $this->request->param('type/s', '');
        //10，查询
        $info = db('order o')
            ->field('o.id as order_id,o.client_ordernum 
                ,g.id as g_id,g.unit_set_flag,g.name as g_name
                ,oe.cost_jiagong_littleSumCost,oe.cost_jiagong_scale
                ,oe.cost_jiagong_sumCostForSale,oe.dress_changkuan_unitPrice
                ,oot.u_out_type,oot.u_scale,oot.u_price_manual,oot.u_scale_changkuan
                ,s.cost as s_cost,s.cost_scale as s_cost_scale
                ')
            ->join('order_ext oe', 'oe.order_id=o.id', 'left')
            ->join('order_outgo oot', "o.id=oot.order_id", 'left')
            ->join('factory ft', "ft.id=o.factory_id", 'left')
            ->join('wx_group g', 'oot.group_id=g.id', 'left')
            ->join('sku s', 'o.sku=s.sku', 'left')
            ->where([
                ['o.id', '=', $order_id],
            ])->find();
        switch (env('env_site')) {
            case 'riwei':
                if ($info['cost_jiagong_littleSumCost'] <= 0) {
                    $info['cost_jiagong_littleSumCost'] = $info['s_cost'];
                    $info['cost_jiagong_scale'] = $info['s_cost_scale'];
                    $info['cost_jiagong_sumCostForSale'] = sprintf("%.2f", $info['s_cost'] * $info['s_cost_scale']);
                    $info['dress_changkuan_unitPrice'] = 0;
                }
                $this->assign('mes_res_code', 0);
                $this->assign('mes_res_msg', '');
                break;
            case 'mimo':
            default:
                if ($info['cost_jiagong_littleSumCost'] <= 0) {//知道还没同步mes的信息，调用接口处理。
                    $res = $this->unitSet_mes_set($info['order_id']);
                    $this->assign('mes_res_code', $res['code']);
                    $this->assign('mes_res_msg', $res['msg']);
                    if ($res['code'] == 0) {
                        $info = db('order o')
                            ->field('o.id as order_id,o.client_ordernum 
                ,g.id as g_id,g.unit_set_flag,g.name as g_name
                ,oe.cost_jiagong_littleSumCost,oe.cost_jiagong_scale
                ,oe.cost_jiagong_sumCostForSale,oe.dress_changkuan_unitPrice
                ,oot.u_out_type,oot.u_scale,oot.u_price_manual,oot.u_scale_changkuan
                ')
                            ->join('order_ext oe', 'oe.order_id=o.id', 'left')
                            ->join('order_outgo oot', "o.id=oot.order_id", 'left')
                            ->join('factory ft', "ft.id=o.factory_id", 'left')
                            ->join('wx_group g', 'oot.group_id=g.id', 'left')
                            ->where([
                                ['o.id', '=', $order_id],
                            ])->find();
                    }
                } else {
                    $this->assign('mes_res_code', 0);
                    $this->assign('mes_res_msg', '');
                }
                break;
        }
        $info['g_id'] = intval($info['g_id']);
        $this->assign('info', $info);
        $u_out_type_array = [
            ['name' => '裁', 'value' => 1, 'selected' => false,],
            ['name' => '车', 'value' => 2, 'selected' => false,],
            ['name' => '尾', 'value' => 3, 'selected' => false,],
            ['name' => '专机', 'value' => 4, 'selected' => false,],
        ];
        if ($info['u_out_type'] != '') {
            $temp = explode(',', $info['u_out_type']);
            foreach ($u_out_type_array as $k => $v) {
                foreach ($temp as $k2 => $v2) {
                    if ($v2 == $v['value']) {
                        $u_out_type_array[$k]['selected'] = true;
                        break;
                    }
                }
            }
        }
        $this->assign('u_out_type_array', $u_out_type_array);
        if ($info['unit_set_flag'] == 2) {
            $this->assign('mes_res_code', 10);
            $this->assign('mes_res_msg', "此{$info['g_name']}，自动审核关闭，不用设置");
        }
        $this->assign('order_id', $order_id);
        $this->assign('type', $type);
        return $this->fetch();
    }

    private function unitSet_mes_set($order_id = '')
    {
        $info = db('order o')
            ->field(' o.id as order_id ,o.client_ordernum ,o.sku ,o.is_auto_import
            ')
            ->join('sku sku', "o.sku=sku.sku", 'left')
            ->join('order_ext oext', 'o.id=oext.order_id', 'left')
            ->where([
                ['o.id', '=', $order_id],
            ])->group('o.id')->find();
        $mesLib = new Mes();
        $mes = intval($info['is_auto_import']);
        $config = [
            'private_key' => env("mes{$mes}.private_key"),
            'app_id' => env("mes{$mes}.app_id"),
            'app_secure' => env("mes{$mes}.app_secure"),
            'host' => env("mes{$mes}.host"),
        ];
        $mesLib->setConfig($config);
        $result = $mesLib->getProduceOrderInfo($info['client_ordernum']);
//        $result = '{"code":0,"info":{"acceptOrderTime":"2022-03-15 21:14:42","clothCostFeeDetail":[{"category":"加工费","clothCostFeeDetail":[{"burningPrintTipFlag":false,"materialMeter":"-","price":"0.40","profitRate":0.0970,"simpleAccount":"-","simpleUse":"-","supplierLoss":"-","supplierProfit":"-","title":"运反腰带完成","unitPrice":"0.40"},{"burningPrintTipFlag":false,"materialMeter":"-","price":"1.06","profitRate":0.0970,"simpleAccount":"-","simpleUse":"-","supplierLoss":"-","supplierProfit":"-","title":"烫朴四线拼袋口/烫袋/点位/贴圆袋1个","unitPrice":"1.06"},{"burningPrintTipFlag":false,"materialMeter":"-","price":"0.20","profitRate":0.0970,"simpleAccount":"-","simpleUse":"-","supplierLoss":"-","supplierProfit":"-","title":"四线合肩","unitPrice":"0.20"},{"burningPrintTipFlag":false,"materialMeter":"-","price":"0.80","profitRate":0.0970,"simpleAccount":"-","simpleUse":"-","supplierLoss":"-","supplierProfit":"-","title":"四线上袖 埋夹","unitPrice":"0.80"},{"burningPrintTipFlag":false,"materialMeter":"-","price":"0.51","profitRate":0.0970,"simpleAccount":"-","simpleUse":"-","supplierLoss":"-","supplierProfit":"-","title":"烫朴 拼袖口 四线上","unitPrice":"0.51"},{"burningPrintTipFlag":false,"materialMeter":"-","price":"0.67","profitRate":0.0970,"simpleAccount":"-","simpleUse":"-","supplierLoss":"-","supplierProfit":"-","title":"烫前襟至后领朴  拷边 合面里后中 扣烫后领","unitPrice":"0.67"},{"burningPrintTipFlag":false,"materialMeter":"-","price":"2.00","profitRate":0.0970,"simpleAccount":"-","simpleUse":"-","supplierLoss":"-","supplierProfit":"-","title":"运反前襟至领顶间暗线 运襟脚  上后领还间边线 固定肩位","unitPrice":"2.00"},{"burningPrintTipFlag":false,"materialMeter":"-","price":"0.20","profitRate":0.0970,"simpleAccount":"-","simpleUse":"-","supplierLoss":"-","supplierProfit":"-","title":"落样间前襟线","unitPrice":"0.20"},{"burningPrintTipFlag":false,"materialMeter":"-","price":"0.48","profitRate":0.0970,"simpleAccount":"-","simpleUse":"-","supplierLoss":"-","supplierProfit":"-","title":"冚下脚 倒针","unitPrice":"0.48"},{"burningPrintTipFlag":false,"materialMeter":"-","price":"0.15","profitRate":0.0970,"simpleAccount":"-","simpleUse":"-","supplierLoss":"-","supplierProfit":"-","title":"订主洗唛","unitPrice":"0.15"}],"littleSumCost":"6.47","scale":2.30,"sumCostDesc":"16.32<br>(含倍率：14.88,含利润：1.44)","sumCostForSale":"14.88","sumCostTotal":"16.32"},{"category":"物料费","clothCostFeeDetail":[{"burningPrintTipFlag":false,"invoiceState":2,"materialMeter":"23.70","price":"23.70","profitRate":0.0970,"simpleAccount":"2.23","simpleUse":"2.45","superTaxRate":"0","superTaxRateDecimal":0.0000,"supplierLoss":"10%","supplierProfit":"-","title":"HA1479#TR粗针华夫格/M00028563","unitPrice":"9.66"},{"burningPrintTipFlag":false,"invoiceState":2,"materialMeter":"0.70","price":"0.70","profitRate":0.0970,"simpleAccount":"0.35","simpleUse":"0.38","superTaxRate":"0","superTaxRateDecimal":0.0000,"supplierLoss":"8%","supplierProfit":"-","title":"BP002弹力朴/F00051175","unitPrice":"1.85"}],"littleSumCost":"24.40","sumCostDesc":"26.76<br>(含利润：2.37)","sumCostTotal":"26.76"},{"category":"面辅料二次工艺","clothCostFeeDetail":[],"littleSumCost":"0","sumCostDesc":"0","sumCostTotal":"0"},{"category":"成衣二次工艺","clothCostFeeDetail":[{"burningPrintTipFlag":false,"materialMeter":"-","price":"1.00","simpleAccount":"1.00","simpleUse":"1.00","supplierLoss":"-","supplierProfit":"-","title":"中东及大码款长款耗时补贴（包含：裁剪、大烫、查货、包装）/加工厂","unitPrice":"1.00"}],"littleSumCost":"1.00","sumCostDesc":"1.0000","sumCostTotal":"1.00"}],"cutBedInfo":[{"quantityInterval":"31","sizeName":"XS"},{"quantityInterval":"20","sizeName":"S"},{"quantityInterval":"51","sizeName":"L"}],"cutBedQty":102,"deliveryTime":"2022-03-30","designCode":"W2020092107051608","isFirst":"","isUrgent":"普通","orderInfo":[{"quantity":30,"sizeName":"XS"},{"quantity":20,"sizeName":"S"},{"quantity":50,"sizeName":"L"}],"orderPrice":"44.09","orderType":"FOB","pic":"https://img.ltwebstatic.com/images3_pi/2021/08/02/16278726274d58d7923e9114dfc68cc1bc359fea0c.jpg","placeOrderTime":"2022-03-15 21:04:03","processCostFee":16.3244570000,"processProfit":1.4434570000,"produceOrderId":8435000,"producer":"外发厂-湖南华盛","quantity":100,"refSku":"","scale":2.30,"secondProcess":[],"sku":"sw2107018851275303","status":"车缝","stockType":"JIT","weavingType":"针织"},"msg":"success"}';
        addLog($result, 'unitSet_mes_set');
        $result = json_decode($result, true);
        if ($result['msg'] != 'success') {
            return ['code' => 100, 'msg' => '同步mes的信息失败', 'data' => $result,];
        }
        //同步order_ext表
        $orderExt = [];
        foreach ($result['info']['clothCostFeeDetail'] as $ck => $cv) {
            if ($cv['category'] == '加工费') {
                $orderExt['cost_jiagong_littleSumCost'] = round($cv['littleSumCost'] ?? 0, 2);
                $orderExt['cost_jiagong_scale'] = round($cv['scale'] ?? 0, 2);
                $orderExt['cost_jiagong_sumCostForSale'] = round($cv['sumCostForSale'] ?? 0, 2);
            }
            $orderExt['dress_changkuan_unitPrice'] = 0;
            if (count($cv['clothCostFeeDetail']) > 0) {
                foreach ($cv['clothCostFeeDetail'] as $kd100 => $vd100) {
                    if (isset($vd100['title'])) {
                        $temp0 = strpos($vd100['title'], '长款');
                        $temp1 = strpos($vd100['title'], '补贴');
                        is_int($temp0)
                        && is_int($temp1)
                        && $orderExt['dress_changkuan_unitPrice'] = round($vd100['unitPrice'] ?? 0, 2);
                    }
                }
            }

        }
        $orderExt != []
        && db('order_ext')->where('order_id', $info['order_id'])->update($orderExt);
        return ['code' => 0, 'msg' => '', 'data' => $result,];
    }

    /**
     * 工厂的委外倍率设置
     * @author zhuguosen 905502314@qq.com
     * @date 2022/3/24
     */
    public function unitSetReadonly()
    {
        if ($this->request->isAjax() || $this->request->param('export/d', 0) || $this->request->param('ajaxflag/d', 0) == 1) {
            //1,参数处理
            $param = [
                'order_id' => $this->request->param('order_id/d', 0),
                'u_out_type' => $this->request->param('u_out_type/s', ''),
                'u_scale' => floatval($this->request->param('u_scale', 0)),
                'u_price_manual' => floatval($this->request->param('u_price_manual', 0)),
                'u_scale_changkuan' => floatval($this->request->param('u_scale_changkuan', 0)),
            ];
            if ($param['u_out_type'] == '') {
                return $this->json(10, '请选择委外类型');
            }
            //$param['u_out_type'] 升序处理
            $temp0 = explode(',', $param['u_out_type']);
            $temp1 = [];
            foreach ($temp0 as $k => $v) {
                intval($v) > 0 && $temp1[] = intval($v);
            }
            sort($temp1);
            $param['u_out_type'] = implode(',', $temp1);
            if ($param['u_scale'] <= 0 && $param['u_price_manual'] <= 0) {
                return $this->json(11, '请设置委外倍率（车缝价）或 手工/专机单价');
            }
            $info = db('order_outgo oot')
                ->where([
                    ['oot.order_id', '=', $param['order_id']],
                ])->find();
            if ($info['group_id'] == 0) {
                return $this->json(10, '请先设置子工厂或分组');
            }
            Db::startTrans();
            try {
                //2,业务->修改表 wx_order_outgo
                $temp = db('order_outgo oot')
                    ->where([
                        ['oot.order_id', '=', $param['order_id']],
                    ])->update([
                        'update_time' => time(),
                        'admin_id' => ADMIN_ID,
                        'status' => 100,
                        'u_out_type' => $param['u_out_type'],
                        'u_scale' => $param['u_scale'],
                        'u_price_manual' => $param['u_price_manual'],
                        'u_scale_changkuan' => $param['u_scale_changkuan'],
                    ]);
                if ($temp != 1) {
                    Db::rollback();
                    return $this->json(12, '设置失败');
                }
                //3,业务log->wx_order_outgo_action_log表修改
                $temp = $this->orderOutgoService->action_log([
                    'type' => 'dispatching_unitSet',
                    'param' => $param,
                ]);
                if ($temp == false) {
                    Db::rollback();
                    return $this->json(14, '设置失败');
                }
                //5,成本->暂无
                //6,财务->暂无
                //7,经验->暂无
                Db::commit();
                return $this->json(1, '保存成功');
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return $this->json(13, '设置失败');
            }
        }
        //1,显示参数处理
        $order_id = $this->request->param('order_id/d', 0);
        $type = $this->request->param('type/s', '');
        $tabData = [];
        $tabData['menu'][] = [
            'title' => '返回计时',
            'url' => "mp/OutNodeProgress/returnTime?order_id={$order_id}&type={$type}",
        ];
        $tabData['menu'][] = [
            'title' => '外协尾部',
            'url' => "mp/OutNodeProgress/outTail?order_id={$order_id}&type={$type}",
        ];
        $tabData['menu'][] = [
            'title' => '委外设置',
            'url' => "mp/OutNodeProgress/unitSetReadonly?order_id={$order_id}&type={$type}",
        ];
        $tabData['current'] = url("mp/OutNodeProgress/unitSetReadonly?order_id={$order_id}&type={$type}");

        //10，查询
        $info = db('order o')
            ->field('o.id as order_id,o.client_ordernum 
                ,g.id as g_id,g.unit_set_flag,g.name as g_name
                ,oe.cost_jiagong_littleSumCost,oe.cost_jiagong_scale
                ,oe.cost_jiagong_sumCostForSale,oe.dress_changkuan_unitPrice
                ,oot.u_out_type,oot.u_scale,oot.u_price_manual,oot.u_scale_changkuan
                ,oot.status,otdr.status as status_otdr
                ')
            ->join('order_ext oe', 'oe.order_id=o.id', 'left')
            ->join('order_outgo oot', "o.id=oot.order_id", 'left')
            ->join('order_outgo_order otdr', "o.id=otdr.order_id", 'left')
            ->join('factory ft', "ft.id=o.factory_id", 'left')
            ->join('wx_group g', 'oot.group_id=g.id', 'left')
            ->where([
                ['o.id', '=', $order_id],
            ])->find();
        if ($info['cost_jiagong_littleSumCost'] <= 0) {//知道还没同步mes的信息，调用接口处理。
            $res = $this->unitSet_mes_set($info['order_id']);
            $this->assign('mes_res_code', $res['code']);
            $this->assign('mes_res_msg', $res['msg']);
            if ($res['code'] == 0) {
                $info = db('order o')
                    ->field('o.id as order_id,o.client_ordernum 
                ,g.id as g_id,g.unit_set_flag,g.name as g_name
                ,oe.cost_jiagong_littleSumCost,oe.cost_jiagong_scale
                ,oe.cost_jiagong_sumCostForSale,oe.dress_changkuan_unitPrice
                ,oot.u_out_type,oot.u_scale,oot.u_price_manual,oot.u_scale_changkuan
                ')
                    ->join('order_ext oe', 'oe.order_id=o.id', 'left')
                    ->join('order_outgo oot', "o.id=oot.order_id", 'left')
                    ->join('factory ft', "ft.id=o.factory_id", 'left')
                    ->join('wx_group g', 'oot.group_id=g.id', 'left')
                    ->where([
                        ['o.id', '=', $order_id],
                    ])->find();
            }
        } else {
            $this->assign('mes_res_code', 0);
            $this->assign('mes_res_msg', '');
        }
        $info['g_id'] = intval($info['g_id']);
        $this->assign('info', $info);
        $u_out_type_array = [
            ['name' => '裁', 'value' => 1, 'selected' => false,],
            ['name' => '车', 'value' => 2, 'selected' => false,],
            ['name' => '尾', 'value' => 3, 'selected' => false,],
            ['name' => '专机', 'value' => 4, 'selected' => false,],
        ];
        if ($info['u_out_type'] != '') {
            $temp = explode(',', $info['u_out_type']);
            foreach ($u_out_type_array as $k => $v) {
                foreach ($temp as $k2 => $v2) {
                    if ($v2 == $v['value']) {
                        $u_out_type_array[$k]['selected'] = true;
                        break;
                    }
                }
            }
        }
        $this->assign('u_out_type_array', $u_out_type_array);
        if ($info['unit_set_flag'] == 2) {
            $this->assign('mes_res_code', 10);
            $this->assign('mes_res_msg', "此{$info['g_name']}，自动审核关闭，不用设置");
        }
        $this->assign('hisiTabData', $tabData);
        $this->assign('hisiTabType', 3);
        $this->assign('order_id', $order_id);
        $this->assign('type', $type);
        return $this->fetch('unit_set');
    }

    /**
     * 高级修改信息
     * @author zhuguosen 905502314@qq.com
     * @date 2022/4/26
     */
    public function super_edit()
    {
        $param = [
            'client_ordernum' => $this->request->param('client_ordernum/s', ''),
            'group_id' => $this->request->param('group_id/d', 0),
        ];
        if ($this->request->isPost()) {// 数据验证
            $info = db('order o')->field('o.id,o.client_ordernum')->where([
                ['o.client_ordernum', '=', $param['client_ordernum']],
            ])->find();
            $orList = db('order_outgo_order')->where(['order_id' => $info['id']])->select();
            foreach ($orList as $k => $v) {
                if ($v['status'] >= 1120) {
                    return $this->json(14, '失败');
                }
            }
            // 启动事务
            Db::startTrans();
            try {
                db('order_outgo')->where(['order_id' => $info['id']])->update([
                    'group_id' => $param['group_id'],
                ]);
                db('order_outgo_action_log')->where(['order_id' => $info['id']])->update([
                    'group_id' => $param['group_id'],
                ]);
                db('order_outgo_order')->where(['order_id' => $info['id']])->update([
                    'factory_child_id' => $param['group_id'],
                ]);
                Db::commit();
                return $this->json(1, '成功');
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return $this->json(13, '失败');
            }
        }
        $info = db('order o')->field('o.id,o.client_ordernum
        ,ft.type as ft_type,ft.id as ft_id,ft.name as ft_name,g.id as g_id,g.name as g_name
        ')
            ->join('factory ft', "ft.id=o.factory_id", 'left')
            ->join('order_outgo oot', "oot.order_id=o.id", 'left')
            ->join('group g', "oot.group_id=g.id", 'left')
            ->where([
                ['o.client_ordernum', '=', $param['client_ordernum']],
            ])->find();
        $assign = [
            'factoryAll' => $this->_factorylist([
                'ft_type' => 1,
            ], true),
            'client_ordernum' => $this->request->param('client_ordernum/s', ''),
            'formData' => $info,
        ];
        return $this->assign($assign)->fetch();
    }

    /**
     * 确认回货 小页面
     * @author zhuguosen 905502314@qq.com
     * @date 2022/5/9
     */
    public function confirmReturnGoodsViewV2()
    {
        $client_ordernum_all = $this->request->param('client_ordernum_all', '');
        $client_ordernum_all = explode(',', $client_ordernum_all);
        $where = [
            ['o.client_ordernum', 'in', $client_ordernum_all],
            ['o.status', 'in', [0, 1]],//99作废
            ['o.client_status', '<>', 99],
        ];
        $where_batch = [
            ['client_ordernum', 'in', $client_ordernum_all],
            ['type', '=', 'return'],
        ];
        $list = db('order o')
            ->field("ft.type as ft_type,ft.name as ft_name,o.id,o.client_ordernum ,o.shipment_time,o.quantity,o.sku,o.type
                ,s.pic,s.ori_pic
                ,g.mobile
                ,oot.sew_save_data,oot.sew_return_material_flag
                ,oot.status as oot_status,oot.batch_status,oot.batch_num
                ,max(bh.num) as num_max
                ,group_concat(distinct os.mid,',', os.size_name,',',os.order_count ,',',os.shicai_count,',',os.jiaohuo_count,',',os.jiaohuo_tail_count,',',os.delivery_count,',',os.daohuo_count,',',os.store_count  SEPARATOR ';') as order_size_list
                ")
            ->join('order_outgo oot', "o.id=oot.order_id", 'left')
            ->join('factory ft', "ft.id=o.factory_id", 'left')
            ->join('sku s', "o.sku=s.sku", 'left')
            ->join('wx_group g', 'oot.group_id=g.id', 'left')
            ->join('order_outgo_batch bh', "o.id=bh.order_id", 'left')
            ->join('order_size os', "o.id=os.order_id", 'left')
            ->where($where)
            ->group('o.id')->select();
        $return_temp = db('order_outgo_batch')->where($where_batch)->select();
        $return_list = [];
        foreach ($return_temp as $k => $v) {
            $return_list[$v['order_id']][] = $v;
        }
        foreach ($list as $k => $v) {
            $list[$k]['num_max'] = intval($v['num_max']);
            $list[$k]['return_list'] = $return_list[$v['id']] ?? [];//整理这数据
            //osList数据设置
            $osList = $this->_deal_order_size_list($v['order_size_list']);
            $list[$k]['osList'] = $osList;
            $list[$k]['osStat'] = ['order_count' => array_sum(array_column($osList, 'order_count')), 'shicai_count' => array_sum(array_column($osList, 'shicai_count')), 'jiaohuo_count' => array_sum(array_column($osList, 'jiaohuo_count')), 'jiaohuo_tail_count' => array_sum(array_column($osList, 'jiaohuo_tail_count')), 'delivery_count' => array_sum(array_column($osList, 'delivery_count')), 'daohuo_count' => array_sum(array_column($osList, 'daohuo_count'))];
            //已回货数 设置
            $this->_get_return_list($list[$k], $list[$k]['osList']);
            //是否只读--已回货已回货数的栏目
            $list[$k]['readonly_return'] = 0;
            $v['batch_status'] == 1 && $v['oot_status'] == 300 && $list[$k]['readonly_return'] = 1;
        }
        $list_last = [];
        foreach ($list as $k => $v) {
            $list_last["_{$v['client_ordernum']}"] = $v;
        }
        $assign = [
            'list' => $list_last,
        ];
        return $this->assign($assign)->fetch();
    }

    private function _get_return_list($info, &$osList)
    {
        foreach ($osList as $k => $v) {
            $osList[$k]['return_num'] = 0;
            if ($info['batch_status'] == 0) {
                foreach ($info['return_list'] as $k2 => $v2) {
                    if ($v['mid'] == $v2['size_mid'] && $v2['type'] == 'return') {
                        $osList[$k]['return_num'] += $v2['count'];
                    }
                }
            } elseif ($v['jiaohuo_count'] > 0) {
                $osList[$k]['return_num'] = $v['jiaohuo_count'];
            }
            $osList[$k]['owe'] = $v['shicai_count'] - intval($osList[$k]['return_num'] ?? 0);
        }
    }

    /**
     * 确认回货
     * @author zhuguosen 905502314@qq.com
     * @date 2022/5/18
     */
    public function confirmReturnGoodsV2()
    {
        //1,参数处理
        $param = $this->request->param();
        //2,wx_order_outgo数据修改
        switch ($param['type_name']) {
            case 'sewing':
                $client_ordernum_all = [];
                foreach ($param['return_goods_num'] as $k => $v) {
                    $client_ordernum_all[] = $k;
                }
                $order_list = db('order o')
                    ->field('o.id,o.client_ordernum')
                    ->where([
                        ['o.client_ordernum', 'in', $client_ordernum_all],
                        ['o.status', '=', 1],//99作废
                    ])->select();
                $param_all = [];
                foreach ($order_list as $k => $v) {
                    $param_all[$k]['order_id'] = $v['id'];
                    $param_all[$k]['client_ordernum'] = $v['client_ordernum'];
                    $param_all[$k]['return_goods_num'] = $param['return_goods_num'][$v['client_ordernum']];
                    $param_all[$k]['owe'] = $param['owe'][$v['client_ordernum']];
                    $param_all[$k]['sew_return_material_flag'] = $param['sew_return_material_flag'][$v['client_ordernum']];
                }
                Db::startTrans();
                try {
                    //2.1,业务->跳过系统-车间工序
                    $res1 = $this->_confirmReturnGoods_real_chejian($param_all);
                    if ($res1 == false) {
                        Db::rollback();
                        return $this->json(11, '设置失败');
                    }
                    //2.2,业务->新系统-数据修改
                    $res2 = $this->_confirmReturnGoods_real($param_all);
                    if ($res2 == false) {
                        Db::rollback();
                        return $this->json(12, '设置失败', [$res2, $param_all]);
                    }
                    Db::commit();
                    return $this->json(1, '');
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    return $this->json(13, '设置失败');
                }
                break;
            case 'sewing_save':
                $client_ordernum_all = [];
                foreach ($param['return_goods_num'] as $k => $v) {
                    $client_ordernum_all[] = $k;
                }
                $order_list = db('order o')
                    ->field('o.id,o.client_ordernum')
                    ->where([
                        ['o.client_ordernum', 'in', $client_ordernum_all],
                        ['o.status', '=', 1],//99作废
                    ])->select();
                $param_all = [];
                foreach ($order_list as $k => $v) {
                    $param_all[$k]['order_id'] = $v['id'];
                    $param_all[$k]['client_ordernum'] = $v['client_ordernum'];
                    $param_all[$k]['return_goods_num'] = $param['return_goods_num'][$v['client_ordernum']];
                    $param_all[$k]['owe'] = $param['owe'][$v['client_ordernum']];
                    $param_all[$k]['sew_return_material_flag'] = $param['sew_return_material_flag'][$v['client_ordernum']];
                }
                Db::startTrans();
                try {
                    //2.2,业务->新系统-数据修改
                    $res2 = $this->_confirmReturnGoods_real_save($param_all);
                    if ($res2 == false) {
                        Db::rollback();
                        return $this->json(12, '设置失败', [$res2, $param_all]);
                    }
                    Db::commit();
                    return $this->json(1, '');
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    return $this->json(13, '设置失败');
                }
                break;
            case 'outgoTail':
                $param['client_ordernum_all'] = explode(',', $param['client_ordernum_all']);
                $order_list = db('order o')
                    ->field('o.id,o.client_ordernum')
                    ->where([
                        ['o.client_ordernum', 'in', $param['client_ordernum_all']],
                        ['o.status', 'in', [0, 1]],//99作废
                    ])->select();
                $param_all = [];
                foreach ($order_list as $k => $v) {
                    $param_all[$k]['order_id'] = $v['id'];
                    $param_all[$k]['client_ordernum'] = $v['client_ordernum'];
                    foreach ($param['client_ordernum_all'] as $k2 => $v2) {
                        if ($v2 == $v['client_ordernum']) {
                            $param_all[$k]['sew_return_goods_num'] = $param['sew_return_goods_num'][$k2];
                            $param_all[$k]['sew_owe'] = $param['sew_owe'][$k2];
                            $param_all[$k]['sew_return_material_flag'] = $param['sew_return_material_flag'][$k2];
                            break;
                        }
                    }
                }
                Db::startTrans();
                try {
                    //2.2,业务->新系统-数据修改
                    $res2 = $this->_confirmReturnGoods_real_outgoTail($param_all);
                    if ($res2 == false) {
                        Db::rollback();
                        return $this->json(12, '设置失败');
                    }
                    Db::commit();
                    return $this->json(1, '');
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    return $this->json(13, '设置失败');
                }
                break;
            case 'finishReturn':
                $param['client_ordernum_all'] = explode(',', $param['client_ordernum_all']);
                $order_list = db('order o')
                    ->field('o.id,o.client_ordernum')
                    ->where([
                        ['o.client_ordernum', 'in', $param['client_ordernum_all']],
                        ['o.status', 'in', [0, 1, 2]],//99作废
                    ])->select();
                $param_all = [];
                foreach ($order_list as $k => $v) {
                    $param_all[$k]['order_id'] = $v['id'];
                    $param_all[$k]['client_ordernum'] = $v['client_ordernum'];
                    foreach ($param['client_ordernum_all'] as $k2 => $v2) {
                        if ($v2 == $v['client_ordernum']) {
                            $param_all[$k]['sew_return_goods_num'] = $param['sew_return_goods_num'][$k2];
                            $param_all[$k]['sew_owe'] = $param['sew_owe'][$k2];
                            $param_all[$k]['sew_return_material_flag'] = $param['sew_return_material_flag'][$k2];
                            break;
                        }
                    }
                }
                Db::startTrans();
                try {
                    //2.2,业务->新系统-数据修改
                    $res2 = $this->_confirmReturnGoods_real_finishReturn($param_all);
                    if ($res2 == false) {
                        Db::rollback();
                        return $this->json(12, '设置失败');
                    }
                    Db::commit();
                    return $this->json(1, '');
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    return $this->json(13, '设置失败');
                }
                break;
            case 'sewing_v2':
            case 'sewing_v2_batch':
                //1，参数处理
                $client_ordernum_all = [];
                foreach ($param['return_goods_num'] as $k => $v) {
                    $client_ordernum_all[] = $k;
                }
                $order_list = db('order o')
                    ->field("o.id,o.client_ordernum,oot.status,oot.batch_status,oot.batch_num
                    ,max(bh.num) as num_max
                    ,group_concat(distinct os.mid,',', os.size_name,',',os.order_count ,',',os.shicai_count,',',os.jiaohuo_count,',',os.jiaohuo_tail_count,',',os.delivery_count,',',os.daohuo_count,',',os.store_count  SEPARATOR ';') as order_size_list
                    ")
                    ->join('order_outgo oot', "o.id=oot.order_id", 'left')
                    ->join('order_outgo_batch bh', "o.id=bh.order_id", 'left')
                    ->join('order_size os', "o.id=os.order_id", 'left')
                    ->where([
                        ['o.client_ordernum', 'in', $client_ordernum_all],
                        ['o.status', 'in', [0, 1]],//99作废
                        ['o.client_status', '<>', 99],
                    ])
                    ->group('o.id')->select();
                foreach ($order_list as $k => $v) {
                    //真回货完成：总状态要大于等于300，加上这状态为1
                    if ($v['status'] == 300 && $v['batch_status'] == 1) {
                        return $this->json(100, '设置失败', $v);
                    }
                }
                $return_temp = db('order_outgo_batch')->where([['client_ordernum', 'in', $client_ordernum_all], ['type', '=', 'return'],])->select();
                $return_list = [];
                foreach ($return_temp as $k => $v) {
                    $return_list[$v['order_id']][] = $v;
                }
                $param_all = [];
                foreach ($order_list as $k => $v) {
                    $param_all[$k]['type_name'] = $param['type_name'];
                    $param_all[$k]['order_id'] = $v['id'];
                    $param_all[$k]['client_ordernum'] = $v['client_ordernum'];
                    $param_all[$k]['status'] = $v['status'];
                    $param_all[$k]['num_max'] = intval($v['num_max']);
                    $param_all[$k]['return_list'] = $return_list[$v['id']] ?? [];
                    $param_all[$k]['osList'] = $this->_deal_order_size_list($v['order_size_list']);
                    $param_all[$k]['return_goods_num'] = $param['return_goods_num'][$v['client_ordernum']];
                    $param_all[$k]['owe'] = $param['owe'][$v['client_ordernum']];
                    $param_all[$k]['sew_return_material_flag'] = $param['sew_return_material_flag'][$v['client_ordernum']];
                }
                Db::startTrans();
                try {
                    //2.1,业务->跳过系统-车间工序
                    if ($param['type_name'] == 'sewing_v2') {
                        $res1 = $this->_confirmReturnGoods_real_chejian($param_all);
                        if ($res1 == false) {
                            Db::rollback();
                            return $this->json(11, '设置失败');
                        }
                    }
                    //2.2,业务->新系统-数据修改
                    $res2 = $this->_confirmReturnGoods_real_v2($param_all);
                    if ($res2 == false) {
                        Db::rollback();
                        return $this->json(12, '设置失败', [$res2, $param_all]);
                    }
                    Db::commit();
                    return $this->json(1, '');
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    return $this->json(13, '设置失败', [$e->getCode(), $e->getMessage(), $e->getFile(), $e->getLine(), $e->getTrace()]);
                }
                break;
            default:
                return $this->json(1000, '设置失败');
                break;
        }
    }

    //order_outgo wx_order_size  wx_order_outgo_action_log表修改
    private function _confirmReturnGoods_real_v2($param_all)
    {
        foreach ($param_all as $k => $v) {
            switch ($v['type_name']) {
                case 'sewing_v2':
                    //0,得出最新的码详情 $v['return_goods_num'] $v['owe']
                    $temp = $this->_batch_return_goods_num($v);
                    if ($temp == false) {
                        return false;
                    }
                    //1,order_outgo表修改
                    $sew_return_goods_num = 0;
                    $sew_owe = 0;
                    foreach ($v['return_goods_num_res'] as $k2 => $v2) {
                        $sew_return_goods_num += $v2;
                    }
                    foreach ($v['owe'] as $k2 => $v2) {
                        $sew_owe += $v2;
                    }
                    if ($sew_return_goods_num <= 0) {
                        return false;
                    }
                    $v['batch_status'] = 1;
                    $v['batch_num'] = $v['num_max'] + 1;
                    if ($v['status'] >= 300) {
                        $update_data = [
                            'status' => 300,
                            'status_after_return_num' => ['inc', 1],
                            'sew_return_goods_num' => $sew_return_goods_num,
                            'sew_owe' => $sew_owe,
                            'sew_return_material_flag' => $v['sew_return_material_flag'],
                            'batch_status' => $v['batch_status'],
                            'batch_num' => $v['batch_num'],
                            'admin_id_return_0_ext' => ADMIN_ID,
                            'time_return_0_ext' => time(),
                            'update_time' => time(),
                        ];
                    } else {
                        $update_data = [
                            'status' => 300,
                            'status_after_return_num' => ['inc', 1],
                            'sew_return_goods_num' => $sew_return_goods_num,
                            'sew_owe' => $sew_owe,
                            'sew_return_material_flag' => $v['sew_return_material_flag'],
                            'batch_status' => $v['batch_status'],
                            'batch_num' => $v['batch_num'],
                            'admin_id_return_0' => ADMIN_ID,
                            'time_return_0' => time(),
                            'update_time' => time(),
                        ];
                    }
                    $temp = db('order_outgo oot')->where([
                        ['oot.order_id', '=', $v['order_id']]
                    ])->update($update_data);
                    if ($temp == 0) {
                        return false;
                    }
                    //1.1,业务order_outgo_batch表的回货记录
                    $temp = $this->orderOutgoService->order_outgo_batch_return('sewing', $v, $sew_return_goods_num, $sew_owe, $v['sew_return_material_flag']);
                    if ($temp != 1) {
                        return false;
                    }
                    //2,业务log->wx_order_outgo_action_log表修改
                    $temp = $this->orderOutgoService->action_log([
                        'type' => 'sewing_confirmReturnGoods_finish',
                        'param' => $v,
                    ]);
                    if ($temp == false) {
                        return false;
                    }
                    //3,业务->wx_order_size表修改
                    foreach ($v['return_goods_num_res'] as $k2 => $v2) {
                        $temp2 = db('order_size ose')->where([
                            ['ose.order_id', '=', $v['order_id']],
                            ['ose.mid', '=', intval($k2)],
                        ])->update([
                            'jiaohuo_count' => intval($v2),
                            'update_time' => time(),
                        ]);
                        if ($temp2 == 0) {
                            return false;
                        }
                    }
                    //5,成本->暂无
                    //6,财务->委外对帐--数据记录
                    $temp = $this->orderOutgoService->order_status_0([
                        'type' => 'sewing_confirmReturnGoods_v2',
                        'param' => $v,
                    ]);
                    if ($temp == false) {
                        return false;
                    }
                    //7,经验->暂无
                    break;
                case 'sewing_v2_batch':
                    //0,得出最新的码详情 $v['return_goods_num'] $v['owe']
                    $temp = $this->_batch_return_goods_num($v);
                    if ($temp == false) {
                        return false;
                    }
                    //1,order_outgo表修改
                    $sew_return_goods_num = 0;
                    $sew_owe = 0;
                    foreach ($v['return_goods_num_res'] as $k2 => $v2) {
                        $sew_return_goods_num += $v2;
                    }
                    foreach ($v['owe'] as $k2 => $v2) {
                        $sew_owe += $v2;
                    }
                    if ($sew_return_goods_num <= 0) {
                        return false;
                    }
                    $v['batch_status'] = 0;
                    $v['batch_num'] = $v['num_max'] + 1;
                    if ($v['status'] >= 300) {
                        $update_data = [
                            'status' => 300,
                            'status_after_return_num' => ['inc', 1],
                            'sew_return_goods_num' => $sew_return_goods_num,
                            'sew_owe' => $sew_owe,
                            'sew_return_material_flag' => $v['sew_return_material_flag'],
                            'batch_status' => $v['batch_status'],
                            'batch_num' => $v['batch_num'],
                            'admin_id_return_0_ext' => ADMIN_ID,
                            'time_return_0_ext' => time(),
                            'update_time' => time(),
                        ];
                    } else {
                        $update_data = [
                            'status' => 300,
                            'status_after_return_num' => ['inc', 1],
                            'sew_return_goods_num' => $sew_return_goods_num,
                            'sew_owe' => $sew_owe,
                            'sew_return_material_flag' => $v['sew_return_material_flag'],
                            'batch_status' => $v['batch_status'],
                            'batch_num' => $v['batch_num'],
                            'admin_id_return_0' => ADMIN_ID,
                            'time_return_0' => time(),
                            'update_time' => time(),
                        ];
                    }
                    $temp = db('order_outgo oot')->where([
                        ['oot.order_id', '=', $v['order_id']]
                    ])->update($update_data);
                    if ($temp == 0) {
                        return false;
                    }
                    //2,业务log->wx_order_outgo_action_log表修改
                    $temp = $this->orderOutgoService->action_log([
                        'type' => 'sewing_confirmReturnGoods_batch',
                        'param' => $v,
                    ]);
                    if ($temp == false) {
                        return false;
                    }
                    //3,业务->wx_order_size表修改 暂无
                    //5,成本->暂无
                    //6,财务->暂无
                    //7,经验->暂无
                    break;
            }
        }
        return true;
    }

    /**
     * 分批回货信息记录
     * wx_order_outgo_batch表的插入
     * @param $info
     * @return bool
     * @author zhuguosen 905502314@qq.com
     * @date 2022/5/10
     */
    private function _batch_return_goods_num(&$info)
    {
        //1,wx_order_outgo_batch表的插入
        $sew_return_goods_num = 0;
        $sew_owe = 0;
        foreach ($info['return_goods_num'] as $k2 => $v2) {
            $sew_return_goods_num += intval($v2);
        }
        foreach ($info['owe'] as $k2 => $v2) {
            $sew_owe += intval($v2);
        }
        if ($sew_return_goods_num <= 0) {
            return false;
        }
        $return_list = [];
        $owe_list = [];
        foreach ($info['osList'] as $k => $v) {
            foreach ($info['return_goods_num'] as $k2 => $v2) {
                if ($v['mid'] == $k2) {
                    $return_list[] = [
                        'order_id' => $info['order_id'],
                        'client_ordernum' => $info['client_ordernum'],
                        'num' => $info['num_max'] + 1,
                        'type' => 'return',
                        'size_mid' => $v['mid'],
                        'size_name' => $v['size_name'],
                        'count' => intval($v2),
                        'admin_id' => ADMIN_ID,
                        'update_time' => time(),
                        'create_time' => time(),
                    ];
                }
            }
            if ($sew_owe != 0) {
                foreach ($info['owe'] as $k2 => $v2) {
                    if ($v['mid'] == $k2) {
                        $owe_list[] = [
                            'order_id' => $info['order_id'],
                            'client_ordernum' => $info['client_ordernum'],
                            'num' => $info['num_max'] + 1,
                            'type' => 'owe',
                            'size_mid' => $v['mid'],
                            'size_name' => $v['size_name'],
                            'count' => intval($v2),
                            'admin_id' => ADMIN_ID,
                            'update_time' => time(),
                            'create_time' => time(),
                        ];
                    }
                }
            }
        }
        if ($return_list != []) {
            db('order_outgo_batch')->insertAll($return_list);
        }
        if ($owe_list != []) {
            db('order_outgo_batch')->insertAll($owe_list);
        }
        //2,统计最终回货数 $info['return_goods_num_res']
        if ($info['num_max'] <= 0) {
            $info['return_goods_num_res'] = $info['return_goods_num'];
            return true;
        }
        $info['return_goods_num_res'] = [];
        foreach ($info['return_goods_num'] as $k => $v) {
            $info['return_goods_num_res'][$k] = $v;
            foreach ($info['return_list'] as $k2 => $v2) {
                $k == $v2['size_mid'] && $info['return_goods_num_res'][$k] += $v2['count'];
            }
        }
        return true;
    }

    /**
     * 查询此sku的库存
     * @author zhuguosen 905502314@qq.com
     * @date 2022/5/11
     */
    public function getStockList()
    {
        $sku = $this->request->param('sku/s', '');
        $stockList = db('sku_stock')->where([['sku', '=', $sku]])
            ->field('sku,size_name,sum(available_count) as available_count,sum(defective_count) as defective_count')
            ->group("sku,size_name")
            ->select();
        $stock_str = '库存：';
        foreach ($stockList as $k => $v) {
            if ($v['available_count'] <= 0) {
                continue;
            }
            $stock_str .= "[{$v['size_name']}:{$v['available_count']}]";
        }
        return $this->json(0, '', $stock_str);
    }
}